Sinan Samet Sinan Samet - 1 month ago 12
React JSX Question

Async action returns Array[0]

I am trying to load data with axios but I can't fetch the data into the state.

My reducer:

import * as types from '../actions/actionTypes';

const initialState = {
fetching: false,
fetched: false,
questions: [],
error: null,
}

export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case types.FETCH_QUESTIONS_SUCCESS:
return {
...state,
questions: action.payload
};
case types.FETCH_QUESTIONS_FAILURE:
return {
...state,
error: action.payload
};
default:
return state;
}
}


My action creator:

import * as types from './actionTypes';
import axios from 'axios';

export function fetchQuestions(city) {
return function (dispatch) {
axios.get('http://rest.learncode.academy/api/test123/tweets')
.then((response) => {
console.log("Test:" + response.data) //This returns [Object Object]
dispatch({type: "FETCH_QUESTIONS_SUCCESS", payload: response.data})
})
.catch((err) => {
dispatch({type: "FETCH_QUESTIONS_FAILURE", payload: err})
})
}
};


The console.log in there does give me [Object Object]. But when I call the action it doesn't put anything in the state
questions


const {questions, actions} = this.props;
const openQuestionOverview = (test) => {
actions.fetchQuestions();
console.log(questions); //Returns Array[0] for questions
}

return(
<TouchableHighlight onPress={openQuestionOverview}>
<Image source={button} />
</TouchableHighlight>
)

Answer

The fact it's returning [Object Object] isn't an issue... that's the String literal representation of the object. For debugging purposes you might want to log it out on two lines or concatenate with stringified JSON.

console.log('Test')
console.log(response.data)

// or 

console.log('Test: ' + JSON.stringify(response.data))

Assuming the response data contains a questions key, the log immediately after fetchQuestions should return [] because that's the initial state and the API is async. So you won't be able to see the state in that same call you're invoking the action. You might want to bind a Text component to the value of JSON.stringify(questions,null,2) so you can ensure the state is being updated properly.