Edit/Update Action Creator in Redux - javascript

export function editPost(props){
const request = axios.put(`http://www.example.com/posts`, props) ;
return{
type: EDIT_POST,
payload: request
};
}
hi,, is this what a proper "Update" action should look like in Redux?
using axios to make the request
the type was created in another file and then imported
Thanks

axios is promise-based, so currently you're returning a payload that doesn't exist. Look for redux-thunk and use it in the following way:
actionCreator() {
return (dispatch) => {
return axios.put('url').then((res) => dispatch({ type: EDIT_POST, payload: res }))
}
}

Related

making a post request inside mapDispatchToProps in react-redux

I'm trying to make a post request inside a function whenever i click on a button.
here is the code of the button
<Button onClick={handleClick}>Add to Cart</Button>
and here is the `handleClick funcion:
const handleClick = (event) => {
event.preventDefault();
props.postCart(itemData.product_name, itemData.product_price);
}
and here i showcase the code of mapDispatchToProps function:
const mapDispatchToProps = dispatch => {
return {
postCart: (productName, productPrice) => dispatch(postAddToCart(productName, productPrice))
}
}
finally the code of postAddToCart:
export const postAddToCart = (productName, productPrice) => {
const email = sessionStorage.getItem('email');
return (dispatch) => {
dispatch(productName, productPrice);
//REST API endpoint
axios.post('http://localhost:8000/api/auth/add-to-cart', {
email:email,
})
.then(resp => {
dispatch({
type: actionTypes.ADDED_TO_CART,
status: resp.status
});
})
.catch(resp => {
dispatch({
type: actionTypes.ADDED_TO_CART,
status: "FAILED"
});
})
}
}
But whenever i click the button Add to cart i get the following error:
Error: Actions must be plain objects. Use custom middleware for async actions.
knowing that i'm using the redux-thunk middleware.
Can you please tell me what's the problem and how can i fix it ? thank you ^^. if i missed something tell me in comments to add it ^^
Your function postAddToCart() returns a "dispatcher", i.e. a function that expects dispatch as an argument.
The error is that you are trying to dispatch this "dispatcher", instead of an "action":
// wrong: calling 'dispatch()'
postCart: (productName, productPrice) => dispatch(postAddToCart( ... ))
// correct: calling the returned dispatcher and pass 'dispatch' as argument
postCart: (productName, productPrice) => postAddToCart( ... )(dispatch)

Use Redux store as input for Post API call

I built an input interface in React and stored the data in a Redux state.
Then, I created a new action for a Post API call. If the "data" parameter is a constant (that I created as a test), everything works fine.
In reality, I'd like to use a key from the Redux state as the data parameter.
In the example, I'm getting an error because props are not defined.
Does it makes sense to connect this action to the state? If yes, how to do it? Thanks a lot!
import axios from 'axios';
export const show_query_action = () => {
return dispatch => {
dispatch(show_query_started_action());
axios({
method: 'post',
url:'http://127.0.0.1:5000/show_query',
data: this.props.reducer_components
})
.then(res => {
dispatch(show_query_success_action(res));
})
.catch(err => {
dispatch(show_query_failure_action(err.message));
});
};
};
const show_query_started_action = () => ({
type: 'ADD_SHOW_QUERY_STARTED'
});
const show_query_success_action = todo => ({
type: 'ADD_SHOW_QUERY_SUCCESS',
payload: {
...todo
}
});
const show_query_failure_action = error => ({
type: 'ADD_SHOW_QUERY_FAILURE',
payload: {
error
}
});
If it needs to be callable with different parameters from a React component you can put the data parameter as a parameter to your action creator:
export const show_query_action = (data) => {
return dispatch => {
dispatch(show_query_started_action());
axios({
method: 'post',
url:'http://127.0.0.1:5000/show_query',
data: data
})
This is also easily testable. If you only call this action with parameters from the redux store, you can use the second parameter from redux-thunk (wich i presume you are using here):
export const show_query_action = () => {
return (dispatch, getState) => {
const data = getState().data; -> you would specify in wich part of the state your data lives, this is just an example
dispatch(show_query_started_action());
axios({
method: 'post',
url:'http://127.0.0.1:5000/show_query',
data: data
})
Hope this helps.

How can I test vuex action which with jest which has an api call inside it?

ASYNC ACTION VUEX : This is async action which will be called from the
component, it consists of an function fetchGaragesData that will make
an api call to fetch data from server.
[ACTION_TYPES.FETCH_CASHLESS_GARAGES]: async (
{ dispatch, commit, state, rootState },
payload
) => {
commit(MUTATION_TYPES.SET_MISC_KEYS, {
fetchingCashlessGaragesInitiated: true,
})
let { insurerSlug, makeId, rtoCode } = payload
const url = ApiUrls.getCashlessGarages + `${insurerSlug}/${makeId}`
const response = await fetchGaragesData(url, rtoCode)
dispatch(ACTION_TYPES.MODIFY_RTO_WISE_GARAGES_DATA, response)
},
IMPLEMENTATION OF fetchGaragesData: this function internally calls
axios get:
export const fetchGaragesData = (url: string, rtoCode: string) => {
return get(url, {
rto_code: rtoCode,
all_states_data: true,
})
}
How can I test action ACTION_TYPES.FETCH_CASHLESS_GARAGES ???
You might be having API mock response. So, in your spec file you need to add the mock response for that particular API call.
Include your file in spec file which has your actual backend API call.
For example:
import someName from 'path of file'
jest.mock('someName', () => ({
fetchGaragesData: jest.fn((url, rtoCode) =>
success({ body:
Here comes your response body
}})
)
url and rtoCode should be the name of the variables used in your API call file.

Accessing redux store in headlessJS

I need to access store in headlessJS in react native to dispatch an action.
I tried
AppRegistry.registerHeadlessTask('didEnterRegion', (beacon) => Util.didEnterRegion.bind(beacon, store));
and in Util.js
const didEnterRegion = async (beacons, store) => {
console.log(beacons);
store.dispatch({
type: FOUND_PLACES_FAIL,
payload: err
});
});
but now I receive the beacons object as an empty object. How do I pass that object too along with the store.
Sorry, so stupid of me.
I just had to pass the params in headlessJS.
AppRegistry.registerHeadlessTask('didEnterRegion', (beacon) => Util.didEnterRegion.bind(beacon, store));
const didEnterRegion = async (store, beacon) => {
console.log(beacon);
store.dispatch({
type: FOUND_PLACES_FAIL,
payload: err
});
});

Appending Props in React-Redux Form using Axios

I have an action that returns dispatch. Right now i am posting props... but i'd like to add a few peices like (uname, role, etc) to the request. What is he easiest way to do so?
I thought something like:
const addlFields = { username: 'newTester', role: 'moderator' }
Any good advice on how to get this done? Im assuming it is not an axios issue since axios and accepting the props obj.
My request
const sendMessageRequest = axios.post(`${POST_MSG_URL}`, props)
.then(response => {
return dispatch => {
dispatch(
{ type: POST_MESSAGE,
payload: sendMessageRequest
}
);
}
});`

Categories

Resources