Search code examples
javascriptreact-nativereact-hooksasync-awaitexpo

Component and Data Disappear after refresh page


I am working on an expo app. I got a situation which my component/data disappear after page refresh, but when I make any kind of changes in my code(such as just adding semicolon) and click save, component/data shows up, then once again, while I click refresh, component/data disappear.

The situation is very similar to the page React component content disappears after page refresh, which state return [ ] after refresh. I have tried all the methods in the page, but none of them work in my case.

The idea here is that, I combine getSign and getLine data to have getFinal data. The page after refresh return [ ]. The page after changes return [data] correctly.

Anything would be helpful. Thank you

  const [Final, setFinal] = useState([]);
  const [Sign, setSign] = useState([]);
  const [Linedata, SetLinedata] = useState([]);      
  useEffect(() => {
    (async () => {
      getSign();
      getLine();
      setFinal(await getFinal());
    })();
  }, [])
  const getFinal =  () => {
    // combine sing data and line data 
return new Promise((resolve)=>{
  const FinalLineData = Sign.map((item, i) => Object.assign({}, item, { Line: Linedata[item['sign']] }))
resolve(FinalLineData)
})

Solution

  • React state resides in memory... when you simply edit and save your code the React code is "hot-reloaded", so the underlying React code is updated and the rendered content is simply re-rendered. But when you reload the page you are dumping whatever was in memory and starting fresh, your entire React app will be remounted and have the initial state.

    If you want data to persist longer than this you'll need to persist it to longer-term storage, like localStorage.

    Basic example uses localStorage to initialize the states and useEffect hooks to persist state changes:

    ...
    
    const [final, setFinal] = useState(
      () => JSON.parse(localStorage.getItem("final")) || []
    );
    const [sign, setSign] = useState(
      () => JSON.parse(localStorage.getItem("sign")) || []
    );
    const [linedata, SetLinedata] = useState(
      () => JSON.parse(localStorage.getItem("linedata")) || []
    );      
    
    useEffect(() => {
      localStorage.setItem("final", JSON.stringify(final));
    }, [final]);
    
    useEffect(() => {
      localStorage.setItem("sign", JSON.stringify(sign));
    }, [sign]);
    
    useEffect(() => {
      localStorage.setItem("linedata", JSON.stringify(linedata));
    }, [linedata]);
    
    ...
    

    Since you are using React-Native you may need to instead use AsyncStorage and handle loading the state slightly differently, e.g. via a separate useEffect hook combined with some loading state.