Hassnian Idrees
Hassnian Idrees

Reputation: 145

Redux state is not updated at time that i acces it

I'm trying to find a course after fetching it from the backend , but when i go to the state after the fetch the state is the initial one . This functions is called when the components is mounted

 findCourse = async () => {
     const { props, state } = this;
     const { idCourse } = state;
     const { loadCourseInfoProps, findCourse } = props;
     await loadCourseInfoProps(idCourse);// goes to the back end and fetches the course and its updated the state
     const course1 = findCourse(idCourse); // this functions should go to the updated state in the store and find the course with the id
     console.log(course1);
   };

The mappers

const mapStateToProps = (state:any) => ({
  findCourse: (id:any) => getCourseSelector(state, id),
});
const mapDispatchToProps = (dispatch:Dispatch) => ({
  loadCourseInfoProps: (id:any) => dispatch(loadCourseInfo(id)),
});
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(CourseInfoN));

The getter that i created

export const getCourseSelector = (state:any, id:number) =>{
  console.log(state)
  return(
  state.courses.courses.find((course:any) => course.course_data.idCourse === id)
)};

And the aync action

export const loadCourseInfo = (id:any) => async (dispatch:Dispatch, getState:any) => {
  dispatch(loadCourseInfoRequest());
  const state = getState();
  if (state.courses.courses.length !== 0) {
    const courseWithId = state.courses.courses.find((course:any) => course.course_data.idCourse === id);
    if (courseWithId.meta.contains_all || !courseWithId) {
      return;
    }
  }
  try {
    const course = await ApiService.courses.getCourse(id);
    console.log(course)
    const formattedCourse = courseFormatter(course);
    formattedCourse.meta.contains_all = true;
    dispatch(loadCourseInfoSuccess(formattedCourse));
    console.log("finished")
  } catch (error) {
    console.log("[error][1]", error);
    dispatch(loadCourseInfoFail(error));
  }
};

In the image you can see that the log of finished is printed and at that point, the mutation is done but the next console.log in the getter the state is still empty the image link: https://i.sstatic.net/Yuglp.png

Upvotes: 0

Views: 45

Answers (1)

Andres
Andres

Reputation: 1012

You shouldn't expect updated state within the same function call. If you want to have new state, you should probably process it in the same action where you received it:

export const loadCourseInfo = (id:any) => async (dispatch:Dispatch, getState:any) => {
  ...
    const course = await ApiService.courses.getCourse(id);
    // use it right here
};

Or you could use updated state on next render.

Upvotes: 1

Related Questions