I'm creating a system with react & redux where i need to fetch some data from an api, i made the action/function and reducer but when i try to access the results on my component and console log them it shows undefined three times than resolves, and when i try to map through the results of course i cant because of undefined thing.[enter image description here][1]
Here is my action function code.
import axios from "axios";
import Cookies from "js-cookie";
export const signIn = () => {
return {
type: 'LOGGED'
};
};
export const getCompaniesAction = (data) => {
return{
type: "GET_COMPANIES",
payload: data
};
};
export function fetchCompanies(){
return(dispatch) => {
return axios.get(`http://ticketing.mydev.loc/api/companies`, {headers:{
Authorization: `Bearer ${Cookies.get('access_token')}`
}}).then(res => res.data.data).then(data => dispatch(getCompaniesAction(data))).catch(err => console.log(err))
}
}
Here is mu reducer function
const companiesReducer = (state = [], action) => {
switch (action.type) {
case 'GET_COMPANIES':
return{
...state,
companies: action.payload
}
default:
return{
...state
}
}
}
export default companiesReducer;
Here is the store
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
const store = createStore(
allReducers, compose(applyMiddleware(thunk), composeEnhancer)
)
Map state to props
const mapStateToProps = (state) => ({
companies: state.companiesReducer.companies
})
export default connect(mapStateToProps, actionCreators)(Company);
component did mount
componentDidMount() {
this.props.fetchCompanies()
}
And here i try to access the data
render(){
if(this.props.companies !== 'undefined'){
console.log(this.props.companies)
}
So my redux devtool shows perfectly state changes, but this console.log in the component shows undefined three times than shows data. Thanks for your time <3
The undefined is as a result of uninitialized state for companies
. Also "undefined"
is a string, not the value undefined
. Try checking like this
render(){
if(this.props.companies !== undefined){
console.log(this.props.companies)
}