I'm trying to use immutability-helper to update my React state asynchronously from multiple sources (API calls). However, it seems to me that this is not the way to go, since state always gets updated with values from a single source only. Can someone explain me why is this the case and how to properly handle updates of my state?
import React from 'react';
import update from 'immutability-helper';
class App extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
updateInterval: 60, // in seconds
apiEndpoints: [
'/stats',
'/common/stats',
'/personal/stats',
'/general_info',
],
items: [
{ itemName: 'One', apiUrl: 'url1', stats: {} },
{ itemName: 'Two', apiUrl: 'url2', stats: {} },
],
};
this.fetchData = this.fetchData.bind(this);
}
componentDidMount() {
this.fetchData();
setInterval(() => this.fetchData(), this.state.updateInterval * 1000);
}
fetchData() {
this.state.apiEndpoints.forEach(endpoint => {
this.state.items.forEach((item, i) => {
fetch(`${item.apiUrl}${endpoint}`)
.then(r => r.json())
.then(res => {
// response from each endpoint contains different keys.
// assign all keys to stats object and set default 0 to
// those which don't exist in response
const stats = {
statsFromFirstEndpoint: res.first_endpoint ? res.first_endpoint : 0,
statsFromSecondEndpoint: res.second_endpoint ? res.second_endpoint : 0,
statsFromThirdEndpoint: res.third_endpoint ? res.third_endpoint : 0,
};
this.setState(update(this.state, {
items: { [i]: { $merge: { stats } } }
}));
})
.catch(e => { /* log error */ });
});
});
}
render() {
return (
<div className="App">
Hiya!
</div>
);
}
}
export default App;
You should use the prevState argument in setState to make sure it always use the latest state:
this.setState(prevState =>
update(prevState, {
items: { [i]: { $merge: { stats } } },
}));
Alternatively, map your requests to an array of promises then setState when all of them resolved:
const promises = this.state.apiEndpoints.map(endPoint =>
Promise.all(this.state.items.map((item, i) =>
fetch(), // add ur fetch code
)));
Promise.all(promises).then(res => this.setState( /* update state */ ));
Related
I have a class component which should display some list values after an API call, in my render function I call a function to populate some other state list (with specific object properties from the fetched list), the problem is that in the render call, the state values are initially empty and as such the component I return is also just empty.
I've tried using componentDidUpdate() but I dont have much of an idea on how to go about using it, it usually gives me an infinite loop.
Here is my relevant code:
class AdminSales extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
data: [],
};
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch("/api/items")
.then((res) => res.json())
.then((items) => this.setState({ items: items }));
}
componentDidUpdate(prevState) {
if (JSON.stringify(prevState.items) == JSON.stringify(this.state.items)) {
// Do nothing
} else {
// This gives infinite loop ...
// this.fetchData();
}
}
populateData() {
this.state.items.forEach(function (item) {
this.state.data.push({
name: item.name,
value: item.quantity,
});
}, this);
}
render() {
// Output shown line: 65
console.log(this.state);
this.populateData();
const { data } = this.state;
return ( ... );
}
}
export default AdminSales;
Any help will be much appreciated.
First of all there are multiple issues in your code
Updating/Mutating state in render
Instead of updating the state using setState, updating the state inplace in populateData method
Also, as #Drew mentioned we don't have to duplicate items into data instead we can store only the required info in the state once after getting the response from the API.
In the meantime while waiting for the response if you want to show a loading info you can do that as well.
Below is the example covering all those points mentioned above.
const mockAPI = () => {
return new Promise((resolve) => setTimeout(() => {
resolve([{id:1, name: "ABC", quantity: 1}, {id: 2, name: "DEF", quantity: 5}, {id: 3, name: "XYZ", quantity: 9}])
}, 500));
}
class AdminSales extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
loading: true
};
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
mockAPI()
.then((res) => {
this.populateData(res);
});
}
populateData = (data) => {
this.setState({
items: data.map(({name, quantity}) => ({
name,
value: quantity
})),
loading: false
})
}
render() {
//console.log(this.state);
const { items, loading } = this.state;
return loading ? <p>Loading...</p> :
items.map(item => (
<div>{item.name}: {item.value}</div>
));
}
}
ReactDOM.render(<AdminSales />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Note: For simplicity I've mocked the backend API with simple setTimeout.
I am using easy-peasy as the state manager of react application
In the actionOn I need to access state of another model, How can I access todos.items in the notes.onAddNote ?
import { createStore, StoreProvider, action, actionOn } from 'easy-peasy';
const todos= {
items: [],
addTodo: action((state, text) => {
state.items.push(text)
})
};
const notes = {
items: [],
addNote: action((state, text) => {
state.items.push(text)
}),
onAddNote: actionOn(
(actions, storeActions) => storeActions.notes.addNote,
(state, target) => {
// HOW TO READ todos items
}
),
};
const models = {
todos,
notes
};
const store = createStore(models);
making onAddNote a thunkOn instead of actionOn
I have functions.js file and it export one function that I want to use in many files.
functions.js
import { API_URL } from "./index";
export const getData = (skip = 0, params = "") => {
this.setState({
loading: true
});
fetch(`${API_URL}items?limit=5&skip=${skip}${params}`, {
method: "GET",
credentials: "include"
})
.then(res => res.json())
.then(res => {
if (res.result.length > 0) {
let array = [];
res.result.map(item => {
let obj = item.data;
obj = Object.assign({ id: item._id }, obj);
array.push(obj);
});
this.setState({
records: array,
loading: false
});
} else {
this.setState({
next: true,
loading: false,
records: []
});
}
})
.catch(err => {
this.setState({
loading: false
});
});
};
hear this is function.js file that gets data from API and set in the state,
now, I want to use this function in items.js
items.js
import { getData } from "./../../config/functions";
import React from "react";
class Customers extends React.Component {
constructor(props) {
super(props);
this.getData = getData.bind(this);
}
componentDidMount() {
this.getData();
}
...
}
Error
TypeError: Cannot read property 'setState' of undefined
I fount this answer How to use state of one component in another file in reactjs? but it did not work for me so help me to change app.js file state from my functions.js file.
You're trying to re-bind this on an arrow function, which you cannot do. Check out this other SO question/answer for more details, but that's your problem. I'm going to edit this post with a suggestion of a more idiomatic way to write this in React.
Edit: OK I wanted to get you an answer quickly so you could unblock yourself and learn a bit more about arrow functions and this binding.
But more than just fixing this, you could improve this code significantly if you separate your api requests from your component. Right now you're mixing them up by trying to set state in your function that fetches data.
import { API_URL } from "./index";
export const getData = (skip = 0, params = "") => {
this.setState({
loading: true
});
fetch(`${API_URL}items?limit=5&skip=${skip}${params}`, {
method: "GET",
credentials: "include"
})
.then(res => res.json())
.then(res => {
// no need to declare an array and then push to it,
// that's what map is for. It will return a new array.
return res.result.map(item => {
// can also be written as return { ...item, id: item._id }
return Object.assign({ id: item._id }, obj)
});
});
// no need to catch here, you can do error handling in your component
};
import { getData } from "./../../config/functions";
import React from "react";
class Customers extends React.Component {
constructor(props) {
super(props);
this.fetchData = this.fetchData.bind(this);
}
componentDidMount() {
this.fetchData();
}
fetchData() {
getData()
.then((results) => {
this.setState({
next: results.length === 0,
records: results,
loading: false
});
})
.catch((err) => {
this.setState({ loading: false })
});
}
...
}
I converted this application
https://codesandbox.io/s/3y77o7vnkp <--Please check this link
into my react-native app and it works perfect. Since I implemented redux and redux-thunk I have a problem with fetching data.
There is a problem. I converted normal functions from this upper link to actions and reducers in react-native. For Example
handleSelect = itemValue => {
this.setState(
{
...this.state,
base: itemValue,
result: null,
},
this.calculate
);
};
TO
actiontypes.js
export const HANDLE_FIRST_SELECT = 'HANDLE_FIRST_SELECT';
action.js
export const handleFirstSelect = itemValue => {
return {
type: actionTypes.HANDLE_FIRST_SELECT,
itemValue: itemValue,
};
};
and reducer.js
const initialState = {
currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR', 'PLN', 'GBP'],
base: 'EUR',
amount: '',
convertTo: 'PLN',
result: '',
date: '',
error: null,
loading: false,
};
const exchangeCurrencies = (state = initialState, action) => {
switch (action.type) {
case actionTypes.HANDLE_FIRST_SELECT:
return {
...state,
base: action.itemValue,
result: null,
};
...
Next step I used mapStateToProps and mapDispatchToProps in my component like this
const mapDispatchToProps = dispatch => {
return {
handleFirstSelect: itemValue =>
dispatch(exchangeCurriencesActions.handleFirstSelect(itemValue)),
...
const mapStateToProps = (state) => {
return {
base: state.base,
amount: state.amount,
convertTo: state.convertTo,
result: state.result,
date: state.date,
};
};
And I'm using now this.props
<PickerComponent
selectedValue={this.props.base}
onValueChange={this.props.handleFirstSelect}
/>
Until then, everything works ok. Now when I download data in this way with react-redux and redux-thunk (action.js) it stops working
export const fetchDataSuccess = data => {
return {
type: actionTypes.FETCH_DATA_SUCCESS,
data: data,
};
};
export const fetchDataFail = error => {
return {
type: actionTypes.FETCH_DATA_FAIL,
error: error,
};
};
export const fetchData = () => {
return dispatch => {
fetch(`https://api.exchangeratesapi.io/latest?base=${this.props.base}`)
.then(res => res.json())
.then(
data => dispatch(fetchDataSuccess(data.rates)),
e => dispatch(fetchDataFail(e)),
);
};
};
next reducer.js
...
case actionTypes.FETCH_DATA_BEGIN:
return {
...state,
loading: true,
error: null,
};
case actionTypes.FETCH_DATA_SUCCESS:
console.log('data', action.data);
return {
...state,
date: action.data.date,
result: action.data.rates,
loading: false,
};
case actionTypes.FETCH_DATA_FAIL:
console.log('data', action.error);
return {
...state,
loading: false,
error: action.error,
};
...
In the next step added function fetchData into mapDispatchToProps and call this in componentDidMount like that
componentDidMount() {
if (this.props.amount === isNaN) {
return;
} else {
try {
this.props.fetchData();
} catch (e) {
console.log('error', e);
}
}
}
and finnaly I add calculations for currencies in mapStateToProps. I change result like that
result: (state.result[state.convertTo] * state.amount).toFixed(4),
and also I added applymiddleware into the store.
AND FINNALY THERE IS A ERROR
import React from 'react';
import HomeContentContainer from '../../containers/HomeContentContainer/HomeContentContainer';
class HomeScreen extends React.Component {
render() {
return <HomeContentContainer />;
}
}
export default HomeScreen;
Anyone know how to resolve this problem? Where and what should I change the code?
Following up on the comments to the question, please do review those...
In mapStateToProps protect your access to state.result, like this perhaps:
result: state.result ? (state.result[state.convertTo] * state.amount).toFixed(4) : null
, where null could also be 0 or whatever, your call. Your mapStateToProps is indeed getting called (at least) once before the API request is completed, so it needs to handle your initial state of state.result.
I find it confusing that the components property result and the state.result are different things, but this is just my opinion about naming.
I am trying to develop a simple image list component with react-redux stack.
This are my actions, reducers, saga and component root definitions -
// Actions
export const getImageListData = () => ({
type: IMAGE_LIST_GET_DATA
});
export const getImageListDataSuccess = (data) => {
console.log("ACTION::SUCCESS", data);
return ({
type: IMAGE_LIST_GET_DATA_SUCCESS,
payload: data
});
};
// Reducers
export default (state = INIT_STATE, action) => {
console.log("REDUCER::", state, action);
switch (action.type) {
case IMAGE_LIST_GET_DATA: return { ...state, isLoading: true };
case IMAGE_LIST_GET_DATA_SUCCESS: return { ...state, items: action.payload.data, isLoading: false };
default: return { ...state };
}
}
// Sagas
import imagesData from "Data/images.json";
function* loadImages() {
try {
const response = yield call(loadImagesAsync);
console.log("SAGA:: ", response);
yield put(getImageListDataSuccess(response));
} catch (error) {
console.log(error);
}
}
const loadImagesAsync = async () => {
const contacts = imagesData;
return await new Promise((success, fail) => {
setTimeout(() => {
success(contacts);
}, 2000);
}).then(response => response).catch(error => error);
};
export function* watchGetImages() {
console.log("ACTION::INIT", IMAGE_LIST_GET_DATA);
yield takeEvery(IMAGE_LIST_GET_DATA, loadImages);
}
export default function* rootSaga() {
yield all([
fork(watchGetImages)
]);
}
Now in the component I am calling - getImageListData action
and with this mapStateToProps and connect provider -
const mapStateToProps = ({ ImageList }) => {
const {items} = ImageList;
return {items};
};
export default connect(
mapStateToProps,
{
getImageListData
}
)(ImageListLayout);
I am mapping the image list response to the component props.
My component definition is as follows -
class ImageListLayout extends Component {
constructor(props) {
super(props);
this.state = {
displayMode: "imagelist",
pageSizes: [8, 12, 24],
selectedPageSize: 8,
categories: [
{label:'Cakes',value:'Cakes',key:0},
{label:'Cupcakes',value:'Cupcakes',key:1},
{label:'Desserts',value:'Desserts',key:2},
],
orderOptions:[
{column: "title",label: "Product Name"},
{column: "category",label: "Category"},
{column: "status",label: "Status"}
],
selectedOrderOption: {column: "title",label: "Product Name"},
dropdownSplitOpen: false,
modalOpen: false,
currentPage: 1,
items: [],
totalItemCount: 0,
totalPage: 1,
search: "",
selectedItems: [],
lastChecked: null,
displayOptionsIsOpen: false,
isLoading:false
};
}
componentDidMount() {
this.dataListRender();
}
dataListRender() {
this.props.getImageListData();
}
render() {
...
}
}
Now in my component I am able to correctly access this.props.items obtained from reducer with action IMAGE_LIST_GET_DATA_SUCCESS, but I also want to update some of the state variables like isLoading, currentPage, totalItemCount, totalPage and since these belong to this component itself and not their parents I do not want to map them to the props but want to update the state of the component and trigger a re-render.
Can someone please tell me what should I be doing to fix this or am i missing anything else here ?
In your current setup I see no reason for you to have isLoading, etc. in the state. You should just map it to props:
const mapStateToProps = ({ ImageList, isLoading }) => {
const {items} = ImageList;
return {items, isLoading};
};
I don't get why you say "and since these belong to this component itself and not their parents I do not want to map them to the props but want to update the state of the component and trigger a re-render." what do parents have to do with anything here?