Reputation: 191
I'm trying to understand React+Redux. So, now I'm trying to fetch data from API, and faced with popular problem: when I change Redux state, it does not refresh my container component.
I read several questions here, most common problems are mutating state, and incorrect connect
usage. I checked my code, everything looks fine. I suppose, that problem is in Reqct hook useState
, in which I call my action generator.
Code:
Action generator
export const requestAccounts = () => ({
type: 'REQUEST_ACCOUNTS'
});
export const receivedAccounts = (data) => ({
type: 'RECEIVED_ACCOUNTS',
data
});
export const requestAccountsError = (errText) => ({
type: 'RECEIVED_ACCOUNTS_ERROR',
errText
});
export function getAccounts(clientRef = 1) {
return async function (dispatch) {
async function fetchData() {
let res;
try {
res = await fetch("https://wstest.grant.ua/stubs/accnts.json", { //добавить парамтер "номер клиента"
method: 'GET' // *GET, POST, PUT, DELETE, etc.
});
if (res.ok) {
let resJson = await res.json();
dispatch(receivedAccounts(resJson.acn_list));
}
else {
dispatch(requestAccountsError('Error during accounts request! Status '+res.status));
}
}
catch (err) {
dispatch(requestAccountsError(err.message));
};
}
dispatch(requestAccounts());
await fetchData();
/*I supposed that my problem depends on async loading,
so I tried to comment all above code and uncomment row below - also,
React did not re-render my component...*/
//dispatch(requestAccountsError("ERROR_MESSAGEEEE"));
}
}
Reducer
const initialState = {
isFetching : false,
isError : false,
errorText : "",
accounts : []
}
export function acnList(state = initialState, action) {
switch (action.type) {
case "RECEIVED_ACCOUNTS":
return Object.assign({}, state, {
isFetching: false,
isError: false,
errorText: "",
accounts: action.acnList
})
/*I tried to write return { errorText: "123" } - also no re-render.. So, problem is not in
mutating previous state*/
case "RECEIVED_ACCOUNTS_ERROR":
return Object.assign({}, state, {
isFetching: false,
isError: true,
errorText: "ERRTEXTTTT",
accounts: []
})
case "REQUEST_ACCOUNTS":
return Object.assign({}, state, {
isFetching: true,
isError: false,
errorText: "",
accounts: []
})
default:
return state
}
}
Container component
import { connect } from 'react-redux'
import AcnListComponent from '../../MainMenuComponents/AcnListComponent'
import {getAccounts} from '../actions/actions'
const mapStateToProps = (state, ownProps) => {
return {
acnList: state.acnList.accounts,
isError: state.acnList.isError,
isFetching: state.acnList.isFetching,
errorText : state.acnList.errorText
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
getAccounts: () => {
dispatch(getAccounts())
}
}
}
const AcnListContainer = connect(
mapStateToProps,
mapDispatchToProps
)(AcnListComponent)
export default AcnListContainer
And finally, part of my React-component code.
//imports
function AcnListComponent(props) {
/*here I can see that props are changed sucessfully (according to state). But no re-render!*/
console.log(props);
const {t} = props;
const [isLoading, setIsLoading] = useState(props.isFetching);
const [accounts, setAccounts] = useState(props.acnList);
const [emptyMessage, setEmptyMessage] = useState(props.errorText);
const [isError, setIsError] = useState(props.isError);
useEffect(() => {
if ((accounts.length === 0) && !isError) {
props.getAccounts();
}
}, []); //I need to call this effect only once, when component renders
//renders
Looks really strange, like magic)
Maybe, I do something wrong with useEffect
, not with Redux? I need to make this request when my component renders, and re-render it with received data.
Upvotes: 0
Views: 163
Reputation: 2948
Just change const [accounts, setAccounts] = useState(props.acnList);
to const accounts = props.acnList;
Learn more on this blog post.
You need to do it to all props that change.
Edit
Long story short:
This is a common mistake of copying the props into state.
Because props change over time and you need to update the state to reflect the props change (so many unecessary re-renders). The best is to use props directly.
Upvotes: 2