I'm not good in react but i code)) I have problem. My flow: customer open "create new user" page -> then create user -> then redirect "Success" page. after that when customer go to "create new user" page again, -> he go "Success" page without creating. I know it is because i use props wrong way how can I fix it?
my Component.js
class addUser extends Component {
handleSubmit(e) {
e.preventDefault();
const user = {
name: this.state.name,
}
this.props.newUser(user);
}
componentDidUpdate(prevProps, prevState){
const { isCreateNewUser } = this.props.isCreateNewUser;
if(isCreateNewUser == true) {
this.props.history.push('/')
}
}
render() {
<form className="add-new-post" autoComplete="off" onSubmit={ this.handleSubmit }>
</form>
}
my reducer.js
export const reducerSubscriptions = function(state = initialState, action) {
switch (action.type) {
case ADD_USER:
return {
...state,
isCreateNewUser: action.payload
}
}
}
my action.js
export const newUser = (subscription) => dispatch => {
axios.post('/api/user/add', subscription)
.then(res => {
dispatch({
type: ADD_USER,
payload: res.data
});
});
}
my solution:
my action.js
export const createUser = (user) => async dispatch => {
const res = await axios.post('/api/user/add', subscription);
dispatch({ type: SOME_ACTION_TYPE, payload: res });
return res;
}
my Component.js
this.props.createUser(user)
.then(data => {
if(data.data[0]){
this.props.history.push('/');
}
}).catch(error => {
console.log("error", error);
})
i don't know is it good or not but it works. thanks