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.
- UI not re-rendering on state update using React Hooks and form submission
- Why is useState not triggering re-render?
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.