Home > other >  React hook not setting object state
React hook not setting object state

Time:04-16

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:"[email protected]"}
    setData(json);
    console.log(data);  // {}  :(
  }, []);

CodePudding user response:

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:"[email protected]"}
    setData(json);
    console.log(data);  // {}  :(
  }
  getUser();
}, []);

CodePudding user response:

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);

CodePudding user response:

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.

  • Related