How to pass a localstorage value as an argument in axios request


I have a React app and I use Express to handle my db queries.

What I want is to pass my user id stored in localstorage into a post request.

(My app is basically a game where users can gain cards to fight against other players, and to do so, I need to update my db when a user receives a card, which is why I’m trying to do the following).
Here’s my code:

import React, {useEffect, useState} from 'react';
import Axios from "axios";
import axios from "axios";

const Cards = () => {

const [card, setCard] = useState([]);
const id = localStorage.getItem("id");
console.log(id) // Output is 1 (correct)

useEffect(() => {
    async function fetchData() {
        try {
            // Below, id should refer to localStorage.getItem("id")
            const res = await'http://localhost:3001/getRandomCard', {id}) 
        } catch (err) {
            console.log('error:', err)

}, []);

return (
            { => <div className={"text-center"} key={}> {}
                <img alt={"Image de " +} className={'activator'} src={'http://localhost/lfl/inc/img/players-ico/' +} style={{width: '100%'}}/>


export default Cards;

And on my app.js:'/getRandomCard', async function (req, res) {

    const id =;

    console.log('userid= ', id) // Output: undefined

    // ...


I’m very new to React, so I’m trying basic stuff, and maybe my code is not the better way to do what I’m actually trying to do, if so, every comment is deeply appreciated.


With the post method, on the second place is object with ‘body’ of the request. So your data is not in the params, but its in the body.

So you have to use

 const id =;

instead of

const id =;

Answered By – Arek Gil

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published