Home > front end >  Functions is executed before the data is taken from state in React Javascript
Functions is executed before the data is taken from state in React Javascript

Time:10-31

So when the visitors visits for the first time, if they don't have those information I require on the localStorage, it should set them then fetch the data. But the problem is it shows as null when I fetches the data. I tried async but I don't know.

So basically I want all of the localStorage and state to be set before the getData functions is runned.

useEffect(() => {
    (async function () {
      try {
        if (localStorage.getItem('language') === null) {
          localStorage.setItem('language', 'en');
          setLanguage('en')
        }

        if (localStorage.getItem('view') === null) {
          localStorage.setItem('view', 'verses');
          setView('verses');
        }

         getData(`${view}_${language}`);

      } catch (e) {
        console.error(e);
      }
    })();
  }, []);

Here is the function it calls:

const getData = async (where) => {
    try {
      const { data: content, error } = await supabase
        .from(where)
        .select('*')
      if (error) throw error;
      if (content) {
        const randomizer = content[Math.floor(Math.random() * content.length)];
        setContent(randomizer);
      }
    } catch (error) {
      alert(error.error_description || error.message)
    } finally {
      // console.log(content.content)
    }
  }

and here are the states:

  const [view, setView] = useState(null);
  const [language, setLanguage] = useState(null);
  const [content, setContent] = useState(null);

CodePudding user response:

Doesn't matter if you keep them inside the async, the state update itself is async, perhaps you can do the following:


const [language, setLanguage] = useState(localStorage.getItem('language')  || 'en');

useEffect(() => {
    localStorage.setItem('language', language); 
}, [language])

// and same for view 

useEffect(() => {
   if(language && view) {
      getData(`${view}_${language}`);
   }
}, [language, view]) 

I assume these states, language and view, are changed somehow in your app, otherwise you most likely don't need to keep them in state.

  • Related