3

In my form I am trying to add my 'userExists' action to determine if the username has already been taken or not. I have asyncValidate working successful with the documentation of redux-form. Now I want to add my action but I don't find any good example to connect this with the need of Promise. I can add my action with the dispatcher but I got an error redux needs to dispatch via Promise.

Is there any example of how to do that?

FormComponent.jsx

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const asyncValidate = (values , dispatch) => {

    /// ?... dispatch(userExists({ email : values.email }))

    return sleep(1000).then(() => {
        // simulate server latency
        if (['john', 'paul', 'george', 'ringo'].includes(values.username)) {
            throw {username: 'That username is taken'}
        }
    })
}

userAction.jsx

export function userExists(params) {

    return (dispatch) => {

        axios.get('http://apiserver.com/api/users.php', {
            params : { ...params }
        })
            .then((response) => {
                console.log(response.data);
                dispatch({ type : "FETCH_USER_FULFILLED", payload : response.data })
            })
            .catch((err) => {
                dispatch({ type : "FETCH_USER_REJECTED", payload : err })
            });
    }
}

userReducer.jsx

export default function reducer(state = {
    user : {
        id : null,
        firstName : null,
        lastName  : null,
        email     : null,
        meta : {
            zipCode      : null,
            streetNumber : null,
            city         : null,
        },
    },
    fetching   : false,
    fetched    : false,
    error      : null

}, action) {

    switch (action.type) {
        case 'FETCH_USER_PENDING' : {
            return {...state,
                fetching : true
            }
            break;
        }
        case "FETCH_USER_REJECTED" : {
            return {...state,
                fetching : false, error : action.payload
            }
            break;
        }
        case "FETCH_USER_FULFILLED" : {
            return {...state,
                fetched : true, user : action.payload
            }
            break;
        }
        case "ADD_USER" : {
            return {...state,
                user : action.payload }
            break;
        }
    }
    return state;
}

store.jsx

import { applyMiddleware, createStore } from 'redux';
import { createLogger } from 'redux-logger';

import thunk from 'redux-thunk';
import promise from 'redux-promise-middleware';
import reducers from './reducers/Reducers.jsx';

const middleware = applyMiddleware(promise(), thunk, createLogger());

export default createStore(reducers, middleware);

1 Answer 1

1

Here is an example of an action asyncValidate with dispatch. I hope this helps.

export const asyncValidate = (values, dispatch) => {

  return new Promise((resolve, reject) => {
    dispatch({
      type: types.GET_USERNAME_DATA,
      promise: client => client.post('/api', values),
    }).then((result) => {
      if (result.data.code !== 200) reject({username: 'That username is taken'});
      else resolve();
    });
  });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.