via
via

Reputation: 503

useState React not updating

I'm having trouble with react useState hook. I have called backend-api and I want to set result to userData.

api called successfully, I can see console.log(response.data). {“message":"ok","data":[{"id":1,"name":"hyu","birth":"2000.1.1","gender":0,"remarks":"test"}]}

here is the code.

import React , {useState, useEffect} from 'react';
const [userData, setUserData] = useState("");

  useEffect(() => {
    const getUser = async () => {
      const response = await axios.get('api/babyinfo');
        console.log(response.data);
        setUserData(response.data);
      }
      getUser();
    },[]);
    console.log(userData); //  userData is still empty

Dose anyone know what is happening and how can I fix it?

Upvotes: 1

Views: 697

Answers (4)

Milind Agrawal
Milind Agrawal

Reputation: 2934

There is no issue in the code, and its just that you are trying to access an array as an object.

Please try this

import React , {useState, useEffect} from 'react';
const [userData, setUserData] = useState({});

  useEffect(() => {
    const getUser = async () => {
      const response = await axios.get('api/babyinfo');
        setUserData(response.data.data[0]);
      }
      getUser();
    },[]);

   return <span>{userData.name}</span>

Upvotes: 2

Hammad Hassan
Hammad Hassan

Reputation: 622

 import React , {useState, useEffect} from 'react';
    const [userData, setUserData] = useState([]);
    
            const getUser = async () => {
               try {
               const response = await axios.get('api/babyinfo');
               console.log(response.data);
               setUserData(response.data.data);
               }catch(err) => {
              console.log(err)
              }
              }
                 
                 useEffect(() => {
                 getUser();
                },[])

Now, You can console your state to see if your state is updated

console.log(userData);
       

Upvotes: 0

Prabhu
Prabhu

Reputation: 758

const [userData, setUserData] = useState([]);

setUserData(response.data.data);

Upvotes: 1

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Set type [ ] initially in userData like

const [userData, setUserData] = useState([]); // here

Upvotes: 1

Related Questions