Fetch data from API wtih Redux - redux

Recently I've been looking into react and redux. I read up the official documentation and tried some ToDo List tutorials. Part 1 is just about react and this is part 2 about redux:
http://www.theodo.fr/blog/2016/03/getting-started-with-react-redux-and-immutable-a-test-driven-tutorial-part-2/
So basically he just sets up a store and initially adds an array of a few todos. Now I don't want my data to be local and I want to fetch it from an API. I'm having a hard time understanding how this actually works. So the code I would use in my action_creators.js is:
export function fetchData() {
return dispatch => {
fetch('http://127.0.0.1:8000/example')
.then(res => res.json())
.then(res => dispatch({
type: FETCH_DATA,
data: res
}))
}
}
Now in the example code for example adding a 'todo':
export function addItem(text) {
return {
type: 'ADD_ITEM',
text
}
}
You aren't dispatching anything, the tutorial does this in the reducer? But when you return dispatch your fetch, does this automatically get dispatched to your store?
If so I have no clue what I should write in my reducer ..
This is the code I have for adding a 'todo':
import {Map} from 'immutable';
function setState(state, newState) {
return state.merge(newState);
}
function fetchData(state) {
return state;
}
function addItem(state, text) {
const itemId = state.get('hostnames').reduce((maxId, item) => Math.max(maxId,item.get('id')), 0) + 1;
const newItem = Map({id: itemId, text: text, status: 'active'});
return state.update('hostnames', (hostnames) => hostnames.push(newItem));
}
export default function(state = Map(), action) {
switch (action.type) {
case 'SET_STATE':
return setState(state, action.state);
case 'ADD_ITEM':
return addItem(state, action.text);
case 'FETCH_DATA':
return fetchData(state);
}
return state;
}
So basically my question is, how do I fetch the data ( if the fetch is wrong now ) and how do I add the fetched data from my api to the store in my reducer.
I just find react and redux pretty complicated so sorry if I'm asking a really noob question or just making big mistakes in the way I want to do something.
Thanks in advance for any help.

imagine your json
{
"data": {
"apple": 1,
"banana": 3,
},
"status": 200,
}
your actions
export function fetchData() {
return dispatch => {
fetch('http://127.0.0.1:8000/example')
.then(res => res.json())
.then((responseData) => {
if(responseData.status === 200){
dispatch(setData(responseData));
}
})
}
}
export function setData(responseData) {
return {type: SET_DATA, data: responseData.data }
}
your reducer
const initialState = { data: null };
export default function(state = initialState, action) {
switch (action.type) {
case 'SET_DATA':
return Object.assign({}, state, {
data: action.data,
})
default:
return state;
}
}
then your state will become
{ data: {
apple: 1,
banana: 3,
}
}

Actually, all your reducers should be pretty dumb and pure (without any side effects). So their only concern is to modify the state and nothing else. Fetching data from the server or any kind of orchestration should be implemented in redux middleware. Look at redux-thunk or redux-saga if you need something more complicated. Hope that helps.

Related

how do I migrate from redux to redux toolkit

I managed to write reducer using createSlice but the action seems to be confusing.
My old reducer :
function listPeopleReducer(state = {
getPeople:{}
}, action){
switch (action.type) {
case D.LIST_PEOPLE: {
return {
...state
, getPeople:action.payload
}
}
default:{}
}
return state
}
By using createSlice from the redux toolkit, I migrated the reducer to this,
const listPeopleReducer = createSlice({
initialState:{getPeople:{}},
name:"listPeople",
reducers:{
listPeople(state,action){
return {
...state,
getPeople : action.payload
}
}
}
})
My old action, makes an api call inside it, with the help of a helper function makeApiRequest (which takes in parameters and returns the response of the api),
export function listPeople(config: any) {
return function (dispatch: any) {
makeApiRequest(config)
.then((resp) => {
dispatch({
type : D.LIST_PEOPLE,
payload : resp.data
})
})
.catch((error) => {
dispatch({
type : D.LIST_PEOPLE,
payload : error
})
})
}
}
With reduxtool kit, we could do something like,
const listPeople = listPeopleReducer.actions.listPeople;
But, how will I write my custom action that contains the helper function makeApiRequest ?
i.e The old Action should be migrated to reduxtoolkit type.
It's definitely tricky when migrating, since there are some major conceptual changes that you must eventually wrap your head around. I had to do it a couple of times before it clicked.
First, when you are creating const listPeopleReducer with createSlice(), that is not actually what you are creating. A slice is a higher level object that can generate action creators and action types for you, and allows you to export reducers and actions FROM it.
Here are the changes I would make to your code:
const peopleSlice = createSlice({
initialState:{getPeople:{}},
name:"people",
reducers:{
listPeople(state,action){
// uses immer under the hood so you can
// safely mutate state here
state.getPeople = action.payload
}
},
extraReducers:
// each thunk you create with `createAsyncThunk()` will
// automatically have: pending/fulfilled/rejected action types
// and you can listen for them here
builder =>
builder.addCase(listPeople.pending, (state,action) => {
// e.g. state.isFetching = true
})
builder.addCase(listPeople.fulfilled, (state,action) => {
// e.g. state.isFetching = false
// result will be in action.payload
})
builder.addCase(listPeople.rejected, (state,action) => {
// e.g. state.isFetching = false
// error will be in action.payload
})
}
})
Then, outside of your slice definition, you can create actions by using createAsyncThunk(), and do like:
export const listPeople = createAsyncThunk(
`people/list`,
async (config, thunkAPI) => {
try {
return makeApiRequest(config)
} catch(error) {
return thunkAPI.rejectWithError(error)
// thunkAPI has access to state and includes
// helper functions like this one
}
}
}
The "Modern Redux with Redux Toolkit" page in the Redux Fundamentals docs tutorial shows how to migrate from hand-written Redux logic to Redux Toolkit.
Your makeApiRequest function would likely be used with Redux Toolkit's createAsyncThunk, except that you should return the result and let createAsyncThunk dispatch the right actions instead of dispatching actions yourself.

Difficulty implementing redux thunk

This is my first time working with redux hooks and I keep receiving the error: "Error: Actions must be plain objects. Use custom middleware for async actions."
I have added the middleware thunk. Following the other peoples questions, I am not sure where I am making the mistake. I'm looking for an explanation on what I am doing wrong and what I should be reading in order to fix it.
Actions:
export const fetchNewsData = () => {
return (dispatch) => {
axios.get('http://localhost:3001/getnews')
.then(response => {
console.log(response.data);
const data = response.data;
dispatch(loadNews(data));
})
.catch(error => {
console.log(error);
dispatch(errorOnNews(error));
});
}
}
export const loadNews = (fetchedData) => {
return {
type: LOAD_NEWS,
payload: fetchedData
}
}
export const errorOnNews = (errorMessage) => {
return {
type: ERROR_ON_NEWS,
payload: errorMessage
}
}
Reducer:
const initialState = {
fetched: false,
data: [],
input: '',
filtered: [],
error: ''
}
const newsReducer = (state = initialState, action) => {
switch(action.type) {
case LOAD_NEWS:
return {
...state,
fetched: true,
data: action.payload
}
case FILTER_NEWS:
return {
...state
}
case ERROR_ON_NEWS:
return {
...state,
error: action.payload
}
default: return state;
}
}
Store:
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import rootReducer from './rootReducer';
const store = createStore(rootReducer, applyMiddleware(thunk));
Component:
const fetch = useDispatch(fetchNewsData());
useEffect(() => {
if(hasFetched){
// work on true condition
} else {
fetch(); // fails on this line.
}
}, []);
useDispatch does not work like this, as it ignores all arguments and just returns you a dispatch function. So you have called dispatch() there, which essentially equals dispatch(undefined) - and the store doesn't know what to make of that action.
Do this instead:
const dispatch = useDispatch();
useEffect(() => {
if(hasFetched){
// work on true condition
} else {
dispatch(fetchNewsData()); // fails on this line.
}
}, []);
Also, generally you are writing a very outdated style of redux here that we do not really recommend to learn or use in new applications any more.
You might have been following an outdated tutorial - as this style requires you to write multiple times the necessary code and is much more error prone.
For up-to-date tutorials featuring modern redux with the official redux toolkit please see the official redux tutorials
Was following a tutorial and creating additional work that was unnessessary. Answer is to:
Cut: const fetch = useDispatch(fetchNewsData());
Change: fetch(); to fetchNewsData();
In this case, I am calling a handling function that will execute the dispatches when required.

Handling errors with redux-toolkit

The information about the error in my case sits deeply in the response, and I'm trying to move my project to redux-toolkit. This is how it used to be:
catch(e) {
let warning
switch (e.response.data.error.message) {
...
}
}
The problem is that redux-toolkit doesn't put that data in the rejected action creator and I have no access to the error message, it puts his message instead of the initial one:
While the original response looks like this:
So how can I retrieve that data?
Per the docs, RTK's createAsyncThunk has default handling for errors - it dispatches a serialized version of the Error instance as action.error.
If you need to customize what goes into the rejected action, it's up to you to catch the initial error yourself, and use rejectWithValue() to decide what goes into the action:
const updateUser = createAsyncThunk(
'users/update',
async (userData, { rejectWithValue }) => {
const { id, ...fields } = userData
try {
const response = await userAPI.updateById(id, fields)
return response.data.user
} catch (err) {
if (!err.response) {
throw err
}
return rejectWithValue(err.response.data)
}
}
)
We use thunkAPI, the second argument in the payloadCreator; containing all of the parameters that are normally passed to a Redux thunk function, as well as additional options: For our example async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue}) is our payloadCreator with the required arguments;
This is an example using fetch api
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
export const getExampleThunk = createAsyncThunk(
'auth/getExampleThunk',
async(obj, {dispatch, getState, rejectWithValue, fulfillWithValue}) => {
try{
const response = await fetch('https://reqrefs.in/api/users/yu');
if (!response.ok) {
return rejectWithValue(response.status)
}
const data = await response.json();
return fulfillWithValue(data)
}catch(error){
throw rejectWithValue(error.message)
}
}
)
Simple example in slice:
const exampleSlice = createSlice({
name: 'example',
initialState: {
httpErr: false,
},
reducers: {
//set your reducers
},
extraReducers: {
[getExampleThunk.pending]: (state, action) => {
//some action here
},
[getExampleThunk.fulfilled]: (state, action) => {
state.httpErr = action.payload;
},
[getExampleThunk.rejected]: (state, action) => {
state.httpErr = action.payload;
}
}
})
Handling Error
Take note:
rejectWithValue - utility (additional option from thunkAPI) that you can return/throw in your action creator to return a rejected response with a defined payload and meta. It will pass whatever value you give it and return it in the payload of the rejected action.
For those that use apisauce (wrapper that uses axios with standardized errors + request/response transforms)
Since apisauce always resolves Promises, you can check !response.ok and handle it with rejectWithValue. (Notice the ! since we want to check if the request is not ok)
export const login = createAsyncThunk(
"auth/login",
async (credentials, { rejectWithValue }) => {
const response = await authAPI.signin(credentials);
if (!response.ok) {
return rejectWithValue(response.data.message);
}
return response.data;
}
);

Redux Observable: How to use action.payload in latter part of chain?

I've ran into this issue quite a few times where I want to access action.payload further down the chain. But by then, the argument passed to mergeMap has already changed to something else.
Given my action looks like this:
{
type: BUY_GEMS,
payload: { value: 123, productIdentifier: "ABC123" }
}
And this epic:
function purchaseGems(action$, store) {
return action$
.ofType(BUY_GEMS)
.mergeMap(action => {
const { productIdentifier } = action.payload; // <-------- works because it's the first mergeMap in this sequence
return Observable.fromPromise(
// Some promise call
).catch(error => Observable.of(buyGemsRejected(error)));
})
.mergeMap(action => {
const { value } = action.payload; // <----------- doesn't work because "action" is now just the response of the Promise above.
...
});
}
How would I do this?
This trick is to just place your second mergeMap inside the closure where the action is available. In fact, even if you didn't need access to it I generally recommend this pattern in redux-observable whereby you isolate your Observable chains inside your single top-level merging strategy operator (mergeMap, switchMap, etc) because it makes future refactoring like this easier as well as easier error isolation (if added).
function purchaseGems(action$, store) {
return action$
.ofType(BUY_GEMS)
.mergeMap(action => {
const { productIdentifier } = action.payload;
return Observable.fromPromise(somePromise)
.catch(error => Observable.of(buyGemsRejected(error)))
.mergeMap(response => {
const { value } = action.payload;
// ...
});
});
}
Your example contained Observable.fromPromise() which I assume is just pseudo code, so I followed suit with Observable.fromPromise(somePromise) for more clarity for other readers.

Why doesn't this thunk update the store?

I have created a thunk that dispatches a bunch of different actions:
export function resetEverything() {
return function (dispatch) {
return Promise.all([
dispatch(updateCurrentColor('blue')),
dispatch(updateCurrentTypeChoice('hot')),
dispatch(updateData('fish', {})),
dispatch(updateData('giraffes', {})),
dispatch(updateData('elephants', {})),
dispatch(updateData('zebras', {})),
]).then(() => console.log('resetEverything called'));
};
}
These actions are also used in the application individually. Individually called, they work fine; the store is updated with the payloads.
However, in this batch operation, all of the actions are dispatched, the console shows "resetEverything called", and even when I look through the Redux extension in Chrome, each of the actions are dispatched with the same structure (with different payload, naturally). But...when I look at the Diff it says (states are equal) and sure enough, examining the State>Tree shows that the store keys haven't been updated at all.
Why isn't this working? Why are the dispatched actions being ignored?
Reducer:
import update from 'immutability-helper';
function reducer(state = initialState, action = {}) {
switch (action.type) {
case UPDATE_CURRENT_COLOR:
return update(state, { currentColor: { $set: action.payload } });
case UPDATE_CURRENT_TYPE_CHOICE:
return update(state, { currentTypeChoice: { $set: action.payload } });
case UPDATE_DATA:
return update(state, { data: { [action.payload.property]: { $merge: action.payload.dataObject } } });
default: return state;
}
}

Resources