Home > Enterprise >  Component responsible to display all my transactions are not updating after submit
Component responsible to display all my transactions are not updating after submit

Time:06-29

I'm using redux toolkit with react and have a basic setup because I'm building a simple expense tracker, so I have two operations: get all transactions and add a new transaction. That's it.

My problem: When I create a new transaction the component responsible for displaying my data does not update and I can only see the changes after refreshing the page. Below you can see my transactionSlice file:

const initialState = {
    transactions: [],
    loading: false,
    error: null,
}

export const getTransactions = createAsyncThunk(
    "transactions/getTransactions",
    async () => {
        const res = await axios.get('http://localhost:8000/transactions')
        return res.data
    }
)

export const addTransaction = createAsyncThunk(
    "transaction/addTransaction",
    async(data) => {
       const res = await axios.post('http://localhost:8000/transactions', data);
        return res.data
    }
)

const transactionsSlice = createSlice({
    name: 'transactions',
    initialState,
    reducers: {},
    extraReducers: {
        [getTransactions.pending]: (state) => {
            state.loading = true;
        },
        [getTransactions.fulfilled]: (state, {payload}) => {
            console.log(payload);
            state.loading = false;
            state.transactions = payload;
            state.error = ''
        },
        [getTransactions.rejected]: (state) => {
            state.loading = false;
            state.error = state.error.message;
        },
        [addTransaction.pending]: (state) => {
            state.loading = true;
        },
        [addTransaction.fulfilled]: (state) => {
            state.loading = false;           
        },
        [addTransaction.rejected]: (state) => {
            state.loading = false;
            state.error = state.error.message;
        }
    }
});

and here is the code from the component where I'm displaying all transactions

 const { transactions, loading } = useSelector(selectAllTransactions);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getTransactions());
  }, [dispatch]);

but when I make a post request my state with all transactions doesn't update immediately. I can only see the changes if I update the page and I'm doing it manually. I'm wondering why is this happening if I have useEffect watching for changes?

AddTransaction.js file :

const [transactionName, setTransactionName] = useState('');
  const [amount, setAmount] = useState('');

  const dispatch = useDispatch();

  const handleSubmit = (e) => {
    e.preventDefault();
    const data = {
      transactionName,
      amount
    }
    
    if(transactionName && amount){
      dispatch(addTransaction(data));
      dispatch(getTransactions());
      setTransactionName('')
      setAmount('');
    }

  }

I've tried to google it but it seems my doubt is so silly that I can't even find an answer for that. Here is my server file:

app.post('/transactions',(req, res) => {
    const {transactionName, amount} = req.body;
    const query = `INSERT INTO transactions (title, amount) 
                        VALUES ("${transactionName}", "${amount}")`

    db.query(query, (err, result) => {
        if(err){
            console.log(err)
        }
        res.send(result)
    })
    
});

Am I missing something? Could someone explain to me why the component responsible to display all transactions are not updating after submit, please?

CodePudding user response:

Try executing getTransactions once addTransaction(data) is finished, not at the same time:

  const handleSubmit = (e) => {
    e.preventDefault();
    const data = {
      transactionName,
      amount
    }
    
    if(transactionName && amount){
      dispatch(addTransaction(data))
        .then(() => {
          dispatch(getTransactions())
          setTransactionName('')
          setAmount('')
        }
    }
  }
  • Related