Jason Maynard
Jason Maynard

Reputation: 359

Get updated state after redux action

I am trying to use a redux action to update the database with the current state after a change.

Ex. removeStock is called and changes the state of stock from ["A", "B", "C"] to ["A", "C"]

immediately after this I am calling updateWatchlist to send the new state to the database. The problem is mapStateToProps is not updated and is sending the original data to the server although the correct data is displayed on the page.

action

///update
export const updateWatchlist = (payload, selected) => async (dispatch: Function, getState) => {
    const response = await axios
        .put(`${API_URL}/api/editWatchlist/${selected}`, {body: payload}, tokenConfig(getState))
}

///Delete
export const removeStock = (payload) => ({
    type: DELETE_STOCK,
    payload,
});

component

const Security = ({index, name, stocks, selected}) => {
    const dispatch = useDispatch();
    const [taskName, setTaskName] =useState(name)

    const removeTask = (e) => {
        e.stopPropagation()
        dispatch(removeStock(index))
        dispatch(updateWatchlist(stocks, selected))
    }    

    return (
        <Row className="list-group-item">
            <div className="item-titles">
                {name}
            </div>
            <button onClick={(e) => removeTask(e)} className="remove-item">
                <i className="glyphicon glyphicon-remove"></i>
            </button>
        </Row>
    );

}

const mapStateToProps = (state) => {
    return {
        stocks: state.Watchlist.stock.watchlist,
    }
}

Upvotes: 0

Views: 377

Answers (1)

Nghi Nguyen
Nghi Nguyen

Reputation: 950

Cause your removeTask call stack hold the original value for stocks variables and 2 parameter of updateWatchlist still refer to that. After the state in redux changed your component is just rerendered and change the sto

    const removeTask = (e) => {
        //// stocks not changed after dispatch(removeStock(index))
        /// it just changed when component rerender 
        e.stopPropagation()
        dispatch(removeStock(index))
        dispatch(updateWatchlist(stocks, selected))
    } 

My suggestion you can use useEffect to observe when the stocks change then update your watchList:

useEffect(()=>{
   dispatch(updateWatchlist(stocks, selected))
},[stocks])

Upvotes: 1

Related Questions