aiiwa aiiwa - 11 days ago 5
React JSX Question

Unable to getState in redux actions

I am unable to getState within my redux actions.js. Following code doesn't post, only prints in console 'i am out!' and throws no errors:

Test.jsx:

...
import { testPost } from './actions';

...
onSubmit (e) {
e.preventDefault();
testPost({
todo: 'test'
});
}


actions.jsx:

export function testPost (todo) {
console.log('i am out!');

return function (dispatch, getState) {
console.log('i am in!');
let id = getState().test.id;
return fetch(`url`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: id,
todo: todo
})
});
}

}


Note that if I comment out following line and hardcode id, it posts well:

return function (dispatch, getState) {


Also, please let me know if it's right expecting 'I am in!' to be printed in the above sample code.

Answer

You can pass the id you need in to your action creator (testPost), that way your actions don't need to know about the state.

For example:

  export function testPost(todo) {
  console.log('i am out!');
  return function(dispatch, id) {
    return fetch(`url`, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        id: id,
        todo: todo
      })
    });
  }
}

Edit

I'd look at the two (free) online courses I noted in my comment, the second of which has a section on retrieving data, but I'd get to understand redux (actions, reducers and their plumbing) first in a simpler use case before fetching data.

Comments