Home > front end >  On page refresh the progress value becomes 0 and moves to the next page React Redux
On page refresh the progress value becomes 0 and moves to the next page React Redux

Time:04-06

I want to save the progress in MongoDB and then display the progress. The progress value is getting calculated and updated. But when I do page refresh the progress value becomes 0 and in between moves to the next page.

const Quiz = (props) => {
   const {progress: lastProgress, userId} = props; 
    const [progress, setProgress] = useState(lastProgress || 0);
    const dispatch = useDispatch();
    const history = useHistory();
  
    const classes = useStyles();
    

useEffect(() => {
    
          async function fetchProgress(){
            try{
          const progress = await api.get(paths.FETCH_USER);
          const newprogress = progress.progress;
          console.log(newprogress   "alpha");
          if (newprogress <= 100) {
            setProgress(Number(newprogress));
          }}
        catch(error){
          console.log(error);
        }
        };
          fetchProgress();
        }, []);
      
      
        useEffect(() => {
          async function updateProgress() {
            try {
              await api.patch(paths.UPDATE_USER, JSON.stringify({progress}))
                console.log(progress   "valueof");
            }
            catch(error){
              console.log("error", error);
            }
          };
          updateProgress();
        }, [progress]);
      
       function handleSubmit(event) {
            event.preventDefault();
             
            const valid = questions.some((q) => !q.value);
            console.log(valid   "questionsalpha");
            if (!valid) {
                dispatch(postAssessment({ responses: questions, id: assessment.id }, history));
            }
            setCurrentQuestion(0);
           setChecked((previousState) => !previousState);
           setTimeout(() => { 
            setChecked(previousState => ({
                 afterPreviousChange: previousState.previousChange
               }))
          }, 1000);
          setProgress((prevProgress)=> prevProgress   10);  
        
        }
        return (
       <Grid item md={4} >
                <Fragment>
                  <Grid item xs={12} md={6} sm={6}>
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <Box sx={{ width: '100%', mr: 1 }}>
                    <LinearProgress variant="determinate" orientation="vertical" value={progress} />
                    </Box>
                    </Box>
                  </Grid>
                </Fragment>
    
              </Grid>
              )
    );

I am able to calculate the value of progress and the value is stored but on page refresh the progress value changes to 0. Do not know what mistake I am making. Any help will be appreciated.

CodePudding user response:

I think all you need is to persist the progress state to longterm storage so it's accessible after a page reload. Use localStorage to persist the progress state when it updates. Lazy initialize the progress state from localStorage. This avoids any issue of accidentally "resetting" the progress back to 0 via the PATCH request.

Example:

const Quiz = (props) => {
  ... 
  const [progress, setProgress] = useState(() => {
    return Number(JSON.parse(localStorage.getItem("progress")) ?? 0);
  });

  ...
    
  useEffect(() => {
    async function fetchProgress() {
      try {
        const { progress } = await api.get(paths.FETCH_USER);
        console.log(progress   "alpha");
        if (progress <= 100) {
          setProgress(Number(progress));
        }
      } catch(error) {
        console.log(error);
      }
    };

    fetchProgress();
  }, []);
      
  useEffect(() => {
    async function updateProgress() {
      try {
        await api.patch(paths.UPDATE_USER, JSON.stringify({ progress }))
        console.log(progress   "valueof");
      } catch(error){
        console.log("error", error);
      }
    };

    updateProgress();
    localStorage.setItem("progress", JSON.stringify(progress));
  }, [progress]);
      
  function handleSubmit(event) {
    event.preventDefault();
    ...
    setProgress((progress) => progress   10);  
  }

  ...
);
  • Related