After user submits a form I dispatched the create course function.
const handleCreateCourse = () => {
dispatch(createCourse(courseData));
// ??
};
How can I get and use the "_id" of newly created course immediately which will come from backend and will be saved in the updated state? So that I can do the following:
const courses = useSelector(state => state.courses);
const handleCreateCourse = () => {
dispatch(createCourse(courseData));
// ??
const newCourse = courses[courses.length-1];
history.push(`/course/${newCourse._id}`);
};
The createCourse function is using redux-thunk and looks like this:
export const createCourse = (course) => async (dispatch) => {
try {
const { data } = await api.createCourse(course);
dispatch({ type: CREATE_COURSE, payload: data });
} catch (error) {
console.log(error);
}
};
You can return API responses in thunk after dispatching the action.
E.g.
import { createStore, applyMiddleware, combineReducers } from 'redux';
import ReduxThunk from 'redux-thunk';
const thunk = ReduxThunk.default;
const api = {
async createCourse(name) {
return { data: { _id: '100', name } };
},
};
function coursesReducer(state = [], action) {
return state;
}
const rootReducer = combineReducers({
courses: coursesReducer,
});
const store = createStore(rootReducer, applyMiddleware(thunk));
const CREATE_COURSE = 'CREATE_COURSE';
export const createCourse = (course) => async (dispatch) => {
try {
const { data } = await api.createCourse(course);
dispatch({ type: CREATE_COURSE, payload: data });
return data;
} catch (error) {
console.log(error);
}
};
const handleCreateCourse = () => {
store.dispatch(createCourse({ name: 'math' })).then((newCourse) => {
console.log('newCourse: ', newCourse);
console.log(`/course/${newCourse._id}`);
});
};
handleCreateCourse();
The exeuction result:
newCourse: { _id: '100', name: { name: 'math' } }
/course/100