0

I am not much familiar with React. Tried to set state as an object by fetching from api. The fetching returns correct object but setting state is not working at all.

  const [data, setData] = useState({});

  useEffect(async () => {
    const res = await fetch("/api/user");
    const json = await res.json();
    console.log(json);  // {name: "Diego", email:"xxxx@xyz.com"}
    setData(json);
    console.log(data);  // {}  :(
  }, []);
Dreamhi
  • 198
  • 1
  • 1
  • 13
  • 1
    Setting state happens asynchronously so it is unreliable to check the state you set just after you set it. If you want to see that the state has been set correctly, use another useEffect and set its dependency to data so that whenever data is set, it can console.log(data). – MrFullStack Apr 15 '22 at 12:12
  • 2
    useState is asynchronous and won’t change state immediately. Try rendering that data. – MORÈ Apr 15 '22 at 12:15
  • Yes. that makes sense! Originally it working well. Thanks all! – Dreamhi Apr 15 '22 at 12:17

3 Answers3

0

Try In this way with Axios

Axios

useEffect(() => {
 const fetchData = async () => {
  try {
    // api request
      const apiData = await axios.get("/api/user");
      if (apiData.data.status === 200) {
        setData((preData) => {
          return [...preData, 
      ...Object.values(apiData.data.data)];
        });
      } else {
        //
      }
    }
  } catch (error) {
  }
};
fetchData ();
}, [])

Note: We should not use a keyword as a variable name, function name or any other identifier.

0

useEffect can't take an async function, but you can define an async function inside the effect and then run it, like this:

useEffect(() => {
  async function getUser() {
    const res = await fetch("/api/user");
    const json = await res.json();
    console.log(json);  // {name: "Diego", email:"xxxx@xyz.com"}
    setData(json);
    console.log(data);  // {}  :(
  }
  getUser();
}, []);
Gøran Cantona
  • 611
  • 4
  • 5
0

You can use parse() method for this problem

I search this problem on google how to convert to object from json data in javascript. I found this link.

https://www.w3schools.com/js/js_json_parse.asp

Sample is here.

const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
    

 let jsonObject = JSON.parse(jsonString);
    

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);