Killua
Killua

Reputation: 11

React table is not updating after new row added

Hi i'm using axios to add a new record and i am trying to update the table after any CRUD operations on the database.

The parent component has MailList and AddMail components. AddMail component has a form control that calls axios POST to add a new record. How do i refresh the table in MailList using react hooks?

export default function MailList() {

  const [mailList, setMailList] = useState([]);

  useEffect(() => {
    axios.get("http://localhost:5243/api/Mail")
      .then(res => {
        setMailList(res.data)
        console.log(res.data)
      })
      .catch(err => console.log(err))
  }, []);

  return(
    <React.Fragment>
      <Title>Recent Mail Scanned</Title>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>ID</TableCell>
            <TableCell>Tracking Number</TableCell>
            <TableCell>Date Scanned</TableCell>
          </TableRow>
          </TableHead>
          <TableBody>
          {mailList.map((m) => (
              <TableRow key={m.mailId}>
              <TableCell>{m.mailId}</TableCell>
                <TableCell>{m.trackingNo}</TableCell>
                <TableCell>{m.dateScanned}</TableCell>
              </TableRow>
            ))}
          </TableBody>
      </Table>
    </React.Fragment> 
  );
}

AddMail

const initialValues = {
  trackingNumber: '',
  dateCreated: new Date(),
}

const [values, setValues] = useState(initialValues);

const handleInputChange = e => {
    const { name, value } = e.target
    setValues({
      ...values,
      [name]: value
    })
  }

let item = {
    trackingNo: values.trackingNumber,
    dateCreated: values.dateCreated
  }

function addMail()
{
   axios.post("http://localhost:5243/api/Mail", item )
}

...
 <Button onClick={addMail}>Save Mail</Button>

Upvotes: 1

Views: 3376

Answers (2)

kazi naeem rayhan
kazi naeem rayhan

Reputation: 36

You must give your useEffect a dependency. Then if there are any changes in the maillist then the page should be changed.

const [mailList, setMailList] = useState([]);

  useEffect(() => {
    axios.get("http://localhost:5243/api/Mail")
      .then(res => {
        setMailList(res.data)
        console.log(res.data)
      })
      .catch(err => console.log(err))
  }, [mailList]);

Upvotes: 1

Rakesh mokariya
Rakesh mokariya

Reputation: 13

You want to add like this in useEffect.

useEffect(()=>{                                                         
   'your code'                                                                                                                                                                          
},[mailList])

Upvotes: 1

Related Questions