0

My code is as follows:

import React,{ useReducer } from 'react';
import { Button, Col, Container, Modal, Row } from 'react-bootstrap';
export default function Click(){
  let reducer = (state, action) => {
    let result = { ...state };
    switch (action.type) {
      case "addWorkLogEntry":
        console.log("addWorkLogEntry");
        break;
      default: break;
    }
    return result;
  }
  const [formItem, updateFormItem] = useReducer(reducer, { requestObj: {worklogs:[]}, selectedWorkLogId: [] });
  let addWorkLogEntry = (e) => {
    updateFormItem({type:"addWorkLogEntry"});   
  }
  return(
    <>
      <Button variant="dark" onClick={addWorkLogEntry}>Add New WorkLog</Button>
    </>
  )
}

When I click on the "Add New WorkLog" button for the first time, the browser console shows the word "addWorkLogEntry" twice.

After that, when I click on the "Add New WorkLog" button, the browser console shows the word "addWorkLogEntry" once only.

Would you tell me what is going on?

Here is my Stackblitz.

The KNVB
  • 3,588
  • 3
  • 29
  • 54
  • Every time you click, you invoke the reducer function. In the reducer, you return a new object called "result". So the state got updated and logged twice. – angel_dust Apr 11 '22 at 08:01
  • 2
    add your reducer outside the react function and your problem will be solved. – adel Apr 11 '22 at 08:10

0 Answers0