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.
(obj) { return { data: [obj] } }??dataarray from JSON API?data: []property... is that what you want?