Le Lance
Le Lance

Reputation: 11

React Redux Axios

in my React / redux / axios app, I create my store like this:

import eventsData from '../api/event';
console.log(eventsData);

const events = [];
Object.assign(events, eventsData);
const defaultState = {
    events
}
export const store = createStore(rootReducer, defaultState);

This is working fine and my events are listet in my component by mapping over it

 {events.map((event, i) => <CalenderItem key={i} i={i} event={event} {...this.props}/>)}

But when I import my data via axios from a JSON, the store gets the data, but the events are not listed. Import and store creation looks then like this:

const events = [];
axios.get("http://#######/src/api/event")
    .then(result => {
        console.log(result.data.events);
        return Object.assign(events, result.data.events);
    });
const defaultState = {
    events
}
export const store = createStore(rootReducer, defaultState);

It's funny, because the console.log of both data looks the same.

Upvotes: 1

Views: 911

Answers (2)

PranavPinarayi
PranavPinarayi

Reputation: 3207

For asynchronous api calls you can use some middleware like thunk. Here is the link of npm package. I think it is working great with axios. https://www.npmjs.com/package/redux-api-handling-middleware

Upvotes: 0

Andrew Burns
Andrew Burns

Reputation: 309

You're using an asynchronous function (axios.get) and then immediately expecting the results in the following lines of code. To perform this properly you want to request the data, and then perform an action to reduce your data into the store.

const events = [];

const defaultState = {
    events
}

export const store = createStore(rootReducer, defaultState);

Then in another part of your application, the following:

axios.get("http://#######/src/api/event").then( data => {
    dispatch({ type: "RECEIVED_DATA", action: { data }})
});

Then in your reducer:

switch ( action, state ) {
    case "RECEIVED_DATA"
        return Object.assign({}, state, action.data)

Upvotes: 8

Related Questions