0

I created a form in React and I have a API that has a JSON API structure, i.e. with the response inside the data: [] property. And I'm using Axios and redux-thunk to fetch the data.

The data coming from the form state has this structure:

{
  title: '',
  phone: '',
  email: '',
  description: ''
}

How do I convert it so it follows the JSON API convention, using axios, redux-thunk, action and reducer:

{
  data: [{
    title: '',
    phone: '',
    email: '',
    description: ''
  }]
}

This is where I'm stuck:

Reducer:

export default function roleReducer(state = [], action) {
  switch(action.type) {
    case types.SAVE_ROLE_SUCCESS:
      return [
        ...state,
        Object.assign({}, action.role)
      ];

    default:
      return state;
  }
}

Actions:

export function saveRoleSuccess(role) {
  return {
    type: types.SAVE_ROLE_SUCCESS,
    role,
  };
}

Thunk:

export function saveRole(role) {
  return (dispatch, getState) => {
    return axios.post(apiUrl, role)
      .then(savedRole => {
        console.log('Role: ', savedRole);
        dispatch(saveRoleSuccess(savedRole));
        console.log('Get state: ', getState());
      })
      .catch(error => {
        if (error) {
          console.log('Oops! Role not saved.', error);
        }
      });
  };
}

I'm not sure where and what to do to format a new data into the JSON API structure.

3
  • This question is very unclear. Are you asking how to put an object into an array? (obj) { return { data: [obj] } }?? Commented Sep 11, 2017 at 19:13
  • @gravityplanx, yes the question is how can I add my data into the data array from JSON API? Commented Sep 11, 2017 at 19:18
  • What do you mean "from JSON API"? The silly little function in my previous comment creates the simple object with a data: [] property... is that what you want? Commented Sep 11, 2017 at 19:21

1 Answer 1

2

Not 100% sure, but I think here:

return axios.post( apiUrl )

You're not actually sending any data. I reckon you want to do:

const dataToPost = { data: [ role ] }; //wrap the role in an array and an object
return axios.post( apiUrl, dataToPost ); //send the data
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your for your response, I've updated my question by adding the the data in the 2nd parameter of axios.post(). Does your answer follow the JSON API structure when I send the data?
I think so - give it a try!
thanks for your answers. It makes sense. Sorry I wasn't sure and I'm not familiar with axios and thunk. But thanks again.

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.