I'm having a bit of trouble getting my application to work how I'd like it. I'm fairly new to React and Redux so bear with me.
Right now I can call this.props.fetchData('usernamehere') to fetch some data about a user, when it's successful it updates this.props.profile which I use to update the React component. The problem with this is handling errors.
I've tried to handle this by adding a FETCH_DATA_ERROR reducer, but the problem I'm having is that when it 404's it still replaces this.props.profile with an empty object instead of just updating this.props.error. Ideally I want to keep the current profile until it successfully finds a new one, and then show the user what the error was with the username they entered by updating this.props.error.
Right now I have the following action creator setup:
import axios from 'axios';
import { FETCH_DATA, FETCH_DATA_ERROR } from './types';
export const ROOT_URL = 'https://api.github.com/users'
export function fetchData(user) {
const request = axios.get(`${ROOT_URL}/${user}`)
.catch(function (error) {
return {
type: FETCH_DATA_ERROR,
payload: error
}
});
return {
type: FETCH_DATA,
payload: request
}
}
And reducer:
import { FETCH_DATA, FETCH_DATA_ERROR } from '../actions/types';
const INITIAL_STATE = { profile: null, error: null }
export default function(state = INITIAL_STATE, action) {
switch(action.type) {
case FETCH_DATA:
return { ...state, profile: action.payload.data };
case FETCH_DATA_ERROR:
return { ...state, error: action.payload };
default:
return state;
}
}
If anyone has any suggestions they would be greatly appreciated. I feel like I'm on the right path but can't seem to figure out where I'm going wrong.
{ type: FETCH_DATA }on athen?Actions must be plain objects. Use custom middleware for async actions.redux-thunkor any other ceremonial crap. A simple way is to write your API call separate and call your actions creators onthenandcatch. Does that make sense?