Functional react component does not re render on button click

Viewed 36

I have a function called ActivityCenter, it has an notification icon button with a badge that displays the count of the notifications that should update once the notification on the right side of the page has been clicked on. It does not update onClick. How do I update it? Here is the picture of the icon button and notification window on the right

Here is the code:

import React from "react";
import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import List from '@mui/material/List';
import "./activityCenter.css"
import Divider from '@mui/material/Divider';
import image from "./633816.png"

import { IconButton } from '@mui/material';
import { Card } from "@mui/material";
import { CardContent } from "@mui/material";
import { useEffect } from "react";
import Axios from "axios";
import { useNavigate } from "react-router-dom";
import Badge from '@mui/material/Badge';
import { setTemplateEngine } from "@syncfusion/ej2-base";




export default function ActivityCenter() {


    const [activities, setActivities] = React.useState([]);
    let row = [];

    useEffect(() => {
        Axios.get("http://localhost:3001/myActions", {
            params: { 'studentID': sessionStorage.getItem("user_id") }
        }).then((res) => {
            setActivities(res.data);
        })
    }, []
    );

    
    const open = () => {
    
        console.log(row);
        console.log(row["action_id"]);
        Axios.post("http://localhost:3001/viewAction", {
            actionID: row["action_id"]
        }).then((res) => {
            alert(res.data);
        });

        if (row["tables"] == "meeting" || row["tables"] == "logged_offences") {
            sessionStorage.setItem("ticket_id_student", row["table_id"]);

            navigate("/MyTickets");
        } else if (row["tables"] == "sessions") {
               
                navigate("/MySessions");
            }
        
        }

    


    const [state, setState] = React.useState({
        right: false,
    });

    const toggleDrawer = (anchor, open) => (event) => {
        if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
            return;
        }

        setState({ ...state, [anchor]: open });
    
    };

    const list = (anchor) => (
        <Box
            sx={{ width: anchor === 'top' || anchor === 'bottom' ? 'auto' : 400, alignSelf: "center", justifyContent: "center", alignItems: "center" }}
            role="presentation"
            onClick={toggleDrawer(anchor, false)}
            onKeyDown={toggleDrawer(anchor, false)}
        >

            <h1 style={{ fontFamily: "Arial, Helvetica, sans-serif" }}>Notifications</h1>
            {activities.map((activity) => (
                <Card raised sx={{ width: "350px", height: "175px", marginTop: "15px", textAlign: "center", marginLeft: "7.25%" }}>
                    <CardContent>
                        <p style={{ textAlign: "left", fontFamily: "Arial, Helvetica, sans-serif" }}>{activity["date"]}</p>
                        <p style={{ fontFamily: "Arial, Helvetica, sans-serif" }}>{activity["action_desc"]}</p>
                        <Button onClick={() => { row = activity; open();  }}>See more</Button>
                    </CardContent>
                </Card>
            ))};


        </Box>
    );

    return (
        <div>
            {['right'].map((anchor) => (
                <React.Fragment key={anchor}>
                    <IconButton className="box" sx={{
                        textAlign: "center",
                        alignItems: "center",
                    }} onClick={toggleDrawer(anchor, true)}><Badge badgeContent={activities.length} color="primary"><img style={{ width: "20px", marginBottom: "4px" }} src={image} /></Badge></IconButton>
                    <Drawer
                        anchor={anchor}
                        open={state[anchor]}
                        onClose={toggleDrawer(anchor, false)}
                    >
                        {list(anchor)}
                    </Drawer>
                </React.Fragment>
            ))}
        </div>
    );
}
1 Answers

You are using the length of the array of activities to determine the notification count. So after click you need to remove that activity from your activities state. Also don't store the selected item in a dedicated array just pass the selected item in your onClick handler.

export default function ActivityCenter() {


    const [activities, setActivities] = React.useState([]);

    useEffect(() => {
        Axios.get("http://localhost:3001/myActions", {
            params: { 'studentID': sessionStorage.getItem("user_id") }
        }).then((res) => {
            setActivities(res.data);
        })
    }, []
    );

    
    const open = (row, idx) => {
        setActivities(activities.splice(idx, 1)); 
        console.log(row);
        console.log(row["action_id"]);
        Axios.post("http://localhost:3001/viewAction", {
            actionID: row["action_id"]
        }).then((res) => {
            alert(res.data);
        });

        if (row["tables"] == "meeting" || row["tables"] == "logged_offences") {
            sessionStorage.setItem("ticket_id_student", row["table_id"]);

            navigate("/MyTickets");
        } else if (row["tables"] == "sessions") {
               
                navigate("/MySessions");
            }
        
        }

    


    const [state, setState] = React.useState({
        right: false,
    });

    const toggleDrawer = (anchor, open) => (event) => {
        if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
            return;
        }

        setState({ ...state, [anchor]: open });
    
    };

    const list = (anchor) => (
        <Box
            sx={{ width: anchor === 'top' || anchor === 'bottom' ? 'auto' : 400, alignSelf: "center", justifyContent: "center", alignItems: "center" }}
            role="presentation"
            onClick={toggleDrawer(anchor, false)}
            onKeyDown={toggleDrawer(anchor, false)}
        >

            <h1 style={{ fontFamily: "Arial, Helvetica, sans-serif" }}>Notifications</h1>
            {activities.map((activity, idx) => (
                <Card raised sx={{ width: "350px", height: "175px", marginTop: "15px", textAlign: "center", marginLeft: "7.25%" }}>
                    <CardContent>
                        <p style={{ textAlign: "left", fontFamily: "Arial, Helvetica, sans-serif" }}>{activity["date"]}</p>
                        <p style={{ fontFamily: "Arial, Helvetica, sans-serif" }}>{activity["action_desc"]}</p>
                        <Button onClick={() => open(activity, idx)}>See more</Button>
                    </CardContent>
                </Card>
            ))};


        </Box>
    );

    return (
        <div>
            {['right'].map((anchor) => (
                <React.Fragment key={anchor}>
                    <IconButton className="box" sx={{
                        textAlign: "center",
                        alignItems: "center",
                    }} onClick={toggleDrawer(anchor, true)}><Badge badgeContent={activities.length} color="primary"><img style={{ width: "20px", marginBottom: "4px" }} src={image} /></Badge></IconButton>
                    <Drawer
                        anchor={anchor}
                        open={state[anchor]}
                        onClose={toggleDrawer(anchor, false)}
                    >
                        {list(anchor)}
                    </Drawer>
                </React.Fragment>
            ))}
        </div>
    );
}
Related