'Store updates but component does not
I'm trying to update the component after a user inputs new data.
Currently on componetDidMount() I call my reducer to fetch data from an API and return it to the component. That works. But when the user updates add a new form and it gets saved in the API, I call the API and the store updates (both redux and console log confirmed this) but the component does not update.
I'm think this could be an aysnc problem but I'm not certain.
Store:
type KnownAction = RecievedInvoicesAction | RequestInvoicesAction | RefreshInvoices;
export const actionCreators = {
requestInvoices: (): AppThunkAction<KnownAction> => (dispatch, getState) => {
const appState = getState();
if (appState && appState.invoices && appState.invoices.isLoading) {
fetch('https://localhost:44304/api/invoices')
.then((response) => response.json())
.then((data) => {
dispatch({
type: 'RECIEVED_INVOICES',
invoices: data,
isLoading: false,
});
toast.success('Invoices loaded 👍', {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
})
});
dispatch({ type: 'REQUEST_INVOICES', isLoading: true});
}
},
refreshInvoices: (): AppThunkAction<KnownAction> => (dispatch) => {
fetch('https://localhost:44304/api/invoices')
.then((response) => response.json())
.then((data) => {
console.log(data);
dispatch({
type: 'REFRESH_INVOICES',
invoices: data,
isLoading: false,
});
});
dispatch({ type: 'REQUEST_INVOICES', isLoading: true});
}
};
// REDUCER
const unloadedState: InvoiceState = { isLoading: true, invoices: [] };
export const reducer: Reducer<InvoiceState> = (
state: InvoiceState | undefined,
incomingAction: Action
): InvoiceState => {
if (state === undefined) {
return unloadedState;
}
const action = incomingAction as KnownAction;
switch (action.type) {
case 'REQUEST_INVOICES' :
return Object.assign({}, state, {
isLoading: action.isLoading
})
case 'RECIEVED_INVOICES':
return Object.assign({}, state, {
invoices: action.invoices,
isLoading: action.isLoading
})
case 'REFRESH_INVOICES':
return Object.assign({}, state, {
invoices: action.invoices,
isLoading: action.isLoading
})
default:
return state;
}
};
Main Component:
class Home extends React.Component<HomeProps, State> {
constructor(SearchInvoiceProps : HomeProps) {
super(SearchInvoiceProps);
this.state = {
queryText : '',
filterBy : 'all',
orderBy : 'asc',
order : 'invoiceDate',
error : '',
invoicesArr : []
}
}
componentDidMount() {
this.ensureDataFetched();
this.setState({
invoicesArr : this.props.invoices
})
}
ensureDataFetched = () => {
this.props.requestInvoices();
}
...
}
export default connect(
(state: ApplicationState) => state.invoices,
InvoiceStore.actionCreators
)(Home as any);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
