-1

I am curious how I would store the data found from an API call into a redux store and then access it. This is the code I am working with. I am unfamiliar with redux and would like a better understanding of how to use it.

const mapStateToProps = state => {
  return {
    test: state.simpleReducer.test
  };
};

const mapDispatchToProps = dispatch => ({
  simpleAction: () => dispatch(simpleAction())
});

class App extends Component {
  weatherData = {};
  componentDidMount = () => {
    this.newAction();
  };

  newAction = async () => {
    let weatherResponse;

    await axios({
      method: "get",
      url: "http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric"
    }).then(function(response) {
      weatherResponse = [...response.data];
    });
    this.weatherData = weatherResponse;
    console.log(this.weatherData);
  };
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Alex
  • 33
  • 7
  • 1
    Does this answer your question? [How to make AJAX request in redux](https://stackoverflow.com/questions/33891669/how-to-make-ajax-request-in-redux) – Emile Bergeron Jan 15 '20 at 21:02

1 Answers1

1

The source of your data doesn’t really matter - data gets into your store by dispatching actions with that data as a payload, and reducers which take that payload and put it into the store.

So when your request is complete you need to dispatch an action, and make sure it is handled in the reducer.

Use the connect function from react-redux to wire up your mapDispatchToProps and mapStateToProps functions to your component so that you can issue the action and consume the resulting updated state.

Dan
  • 2,830
  • 19
  • 37
  • This was helpful to visualize how reducers work but I am still a bit confused on how the data is returned as a payload in this instance. I need to pass the data found in "newaction" to the mapDispatchToProps constant and then connect the props. – Alex Jan 15 '20 at 22:35
  • I think you need to follow some tutorials / read the docs of redux / react-redux. Maybe follow Dan abramovs introduction to redux on egghead if it’s still there – Dan Jan 15 '20 at 23:14