0

I am creating a reactjs application which will be a marks & gradebook. I am using a useEffect() that triggers on change of the URL parameters from react router that should load content via axios and update the state, triggering a re-render so the form displays the correct record.

The useEffect() does fire, axios retrieves the data but the state is not updated.

I am aware of the following questions indicating the need to use the spread operator to update the state, which I am using.

The relevant portion of my code follows.

export default function AssessmentEditPage() {
    const params = useParams();
    const history = useHistory();
    const [assessment, setAssessment] = useState();
    const [presentToast, dismiss] = useIonToast();
    const data = new DataProvider();

    useEffect(()=>{
        data.getAssessment(params.classid, params.assessmentid) // axios fetch handler
        .then((newAssessment)=>{
            setAssessment({...newAssessment});
            presentToast({color:"success", message:"Loaded "+newAssessment.classid+" / "+newAssessment.assessmentid, duration:500});
        }).catch((err)=>{
            presentToast({color:"danger", message:"Network error", duration:3000});
        })
    }, [params])

The ionToast() pops up to show that axios has loaded the record from the new assessment, but when I put a console.log(assessment.classid, assessment.assessmentid); immediately before the return() function it shows that the state values have not updated as it renders and the following screenshot extract shows the form hasn't rendered with the new route. https://imgur.com/a/gBowmrR

Any insight into what is going on is much appreciated. I'm half tempted to migrate back to a class component if I can't work it out soon.

  • Someone closed this question pointing to https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately I get that the change to `assessments` is asynchronous but the update to assessment doesn't fire at any time. The following little useEffect() that is monitoring for changes in assessment never prints the correct record. ```jsx useEffect(()=>{ console.log("assessment", assessment); }, [assessment]) ``` – Paul Baumgarten Jul 27 '21 at 04:04

0 Answers0