0

I'm trying the fetch data from a json API and setting it to a state. Currently using visual studio code with a pixel 4 emulator.

When I try to update my state inside of a useEffect method on the emulator's first launch or on reload, it doesn't change. If I save in vs code, the data in state updates as intended.

...
import React, {useState, useEffect} from 'react';
import {getJsonData} from './getJsonData';

const myApp = () => {
    const [state, setState] = useState({
      isLoading: true,
      data: null,
    });

    const updateState = data => {
      console.log(data); //Logs the correct Json data everytime
      setState(state => ({...state, isLoading: false, data: data}));
      console.log(state.isLoading); //Doesn't update on reload (updates only on save)
      console.log(state.data); //Same as above
    };

    useEffect(() => {
      getJsonData().then(data => updateState(data));
    }, []);

    return (
      <View>
        <Text>{state.data.title}</Text>
        <Text>{data.data.completed}</Text>
      </View>
    );
}

And this is the getJsonData( ) function:

export async function getJsonData() {
  try {
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    let responseJson = await response.json();
    return responseJson;
  } catch (error) {
    console.error(error);
  }
}

I ultimately want the state to update on the application's first run, on reload, as well as each time I call a certain reloadApp( ) function.

If the above code is not the best practice, please don't hold back to correct me as I'm just learning about states.

1 Answer 1

1

setState function is asynchronous. So console.log immediately after setState will give old value but not the new value.

Also why don't you seperate the states like

const [isLoading,setIsLoading]=useState(true);
const [data,setData] = useState(null);

and set them separately so your code looks better.

in updateState(jsonData) you can do then

setIsloading(false);
setData(jsonData);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh I see, I was so focused on the log that I didn't notice the view was updating. Also, thanks for the tips.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.