0

I want to immediately see the cookbook state variable filled with the data from the API get request. It is not updating in time for the likedByUser function. If I add cookbook as a dependency in the useEffect() dependency array, then it goes into an infinite rendering loop. Any ways for me to see the updated cookbook array by the time I get to the likedByUser function?

const RecipeList = (props) => {
    const [recipes, setRecipes] = useState([]);
    const [cookbook, setCookbook] = useState([]);
    const cookbookURL = 'https://url';

    const getCookbook = async () => {
        const axiosAuth = await axiosWithAuth();
        const res = await axiosAuth.get(cookbookURL);  //resolves successfully
        setCookbook(res.data);
    }

    const likedByUser = () => {
        console.log('cookbook',cookbook);  //cookbook comes back as an empty array
    }

    useEffect(() =>{
        getCookbook();
        likedByUser();  //I want to access the cookbook state variable here
        setRecipes(props.recipes);
    },[]);

    return <View>{cookbook.map(recp => <Recipe recipe={recp} />)}</View>
Avi
  • 1,424
  • 1
  • 11
  • 32
Amir
  • 1,422
  • 1
  • 15
  • 28
  • @chev here is the question in a fresh post. – Amir Nov 13 '19 at 18:09
  • Can you not just move the `likedByUser()` method in the getCookbook call? – ageoff Nov 13 '19 at 18:46
  • @ageoff. that's what I ended up doing. Just trying to understand how to update the state variables immediately. – Amir Nov 13 '19 at 19:07
  • Here is some more details: https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync pretty much... setState is async. The component needs to re-render in order to get the new values of the state. You cannot immediately access the new state. – ageoff Nov 13 '19 at 19:16

0 Answers0