I would like guidance on how to use onClick to toggle the opening and closing of components, and also how to dispatch a close action

i use createSlice from redux toolkit to create my reducers, where I defined the states

below is the code for my store in ./root/app/store.js

import { configureStore } from "@reduxjs/toolkit";
import calendarReducer from '../features/calendarSlice'
import windowReducer from '../features/windowSlice'
import startReducer from '../features/startSlice'

export const store = configureStore({
    reducer: {
        calendar: calendarReducer,
        window: windowReducer,
        start: startReducer
    },
})

and here is the code for my calendarSlice located at ./root/features/calendarSlice.jsx

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
    value: false
}

export const calendarSlice = createSlice({
    name: "calendar",
    initialState,
    reducers: {
        openCalendar : (state) => {
            state.value = true
        },
        closeCalendar: (state) => {
            state.value = false
        },
        closeCalendarOnOtherLayoutsClick: (state) => {
            state.value = false
        }
        
    }
});

export const {openCalendar, closeCalendar} = calendarSlice.actions
export default calendarSlice.reducer

and this is my startSlice in ./root/features/startSlice.jsx

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
    value: false
}

export const startSlice = createSlice({
    name:'start',
    initialState,
    reducers: {
        openStart: (state) => {
            state.value = true
        },
        closeStart: (state) => {
            state.value = false
        }
    }
});

export const {openStart, closeStart} = startSlice.actions
export default startSlice.reducer

The following code showcases my main component with imported components like calendar and start. When clicking on the clock, the calendar component opens upon the first click and closes on the second click. However, when directly clicking on the calendar, it closes itself. I am looking for solutions using Redux actions.

import styles from "./dock.module.scss";
import { useRef } from "react";
import Image from "next/image";
import { openCalendar,closeCalendar  } from '../../../features/calendarSlice'
import { openStart, closeStart } from '../../../features/startSlice'
import { useDispatch, useSelector } from 'react-redux'
import Start from '../start/Start'
import Calendar from "./Calendar";

// Main Dock Component Code

...

view of an open calendar

Facing issues where when start is open and clicking on the calendar should close the start without conflicts in dispatching actions

Answer №1

In order to make your component work properly, you must include a payload in your slices and then dispatch the value in your component.

calendarSlice.jsx

export const calendarSlice = createSlice({
        name: "calendar",
        initialState: {
            value: false
        },
        reducers: {
            openCalendar: (state, action) => {
                state.value = action.payload
            },
            // or with destructuring action
            openCalendar: (state, { payload }) => {
                state.value = payload
            }
        }
    });
    

your component.jsx

const handleClick = (e) => {
       e.preventDefault();
       dispatch(openCalendar(!value));
    };
    

For a simple demo, please check out this link: Stackblitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing a hydration error when utilizing a table in Next.js?

When attempting to use the tr tag in my code, I encountered an error message that reads: Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. import React from 'react' import {useS ...

Unable to find the 'ipfs-http-client' module in the React application

I have encountered an issue with the ipfs-http-client package in my React application. Currently, I am utilizing node 16.14.0 https://i.stack.imgur.com/IDToH.png The specific error message is: https://i.stack.imgur.com/59swB.png Even when I Ctrl + Clic ...

When invoking the fetch method on the PHP controller, it encounters an error during the execution of

Here is an error I encountered while working with ReactJS: VM345:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input To provide some context, I have a PHP controller with a delete endpoint. Below is the code snippet for this endpoint. php c ...

How to resolve a TypeError saying "Object(...) is not a function"?

I've been attempting to display material-ui tabs as a component on another page, but I'm encountering an error that causes the code to break when loading the page with this component. I've tried two different methods of rendering this compo ...

The Netlify deployment encountered an error: Module not found - Unable to resolve 'react-icons/SI'

When I deploy my app to Netlify, I encounter a 'Module not found' error even though it works fine on desktop. Do I need to push my Node_modules to GitHub for this to work, or is Netlify supposed to download all the dependencies from package.json? ...

Using Material-UI checkboxes with React Hook Form for managing arrays

I am having trouble retrieving values from a checkbox array const schema = yup.object().shape({ modules: yup.array(), }); component {role === "user" && divisions.map((division, i) => ( <Box key={ ...

Creating a chat interface with chat bubbles in React JS can be done by implementing components such as Message

Having some JSON data stored in dummyData, I am seeking guidance on how to position chat bubbles on the left and right based on the direction. My framework of choice is Material UI along with the context API. The attached image serves as a visual reference ...

Issue with reCAPTCHA callback in Firebase Phone Authentication not functioning as expected

I have been working on integrating phone authentication into my NextJS website. I added the reCAPTCHA code within my useEffect, but for some reason, it does not get triggered when the button with the specified id is clicked. Surprisingly, there are no erro ...

ReactJS - troubleshooting webcam video stream issue

I can't figure out why this code is not working properly. I am able to access the camera stream and see the light on my camera indicating that it's working, but the stream doesn't seem to be attaching correctly. class VideoOutput extends ...

Multer throws an error when uploading files due to an unexpected field issue

Hello, I am currently working on creating a file upload API using React and Express. To achieve this, I decided to use Muster. However, when I send an Axis request from the client, I encounter an error from the server. Error: MulterError: Unexpected fie ...

Struggling with declaring generic types in TypeScript can be a challenge

Struggling with declaring the type while creating a hook named useUpdate, here's the code: type CallBack<T extends readonly any[]> = ( ...args: T ) => void | (() => void | undefined); function useUpdate<T extends readonly any[]>( ...

Tips on resolving the Warning message: "The event handler property `onExited` is a known property in StatusSnackbar component, but it will

When using the StatusSnackbar component, I encountered a warning about a known event handler property onExited. How can I resolve this issue? Component: import Snackbar from '@material-ui/core/Snackbar' import { withStyles } from '@material ...

Launch the dev server in React

Begin by cloning the git code in React. Next, make sure to install npm package manager. Encountered Problem: I am facing an issue with running the dev-server. I have tried the following command in the cmd prompt: 1. npm run dev-server "Here is a sample ...

Encountering an issue when trying to dynamically import React Material UI Icons

Hey there, I'm currently working on dynamically loading icons from MUI using the following code snippet: import React from "react"; import * as MuiIcons from "@mui/icons-material"; console.log("MuiIcons: ", MuiIcons); co ...

Seeking the "onChange" functionality while implementing the "addEventListener" method

I've been busy with a React project lately. Instead of adding 'onChange' to each button within the html object like this: <input type='text' onChange={myFunction} /> I'd prefer to include it in the JS code like so: doc ...

The process of integrating markdown markdown syntax into a React component using MDX

What is the most effective method to incorporate content from a markdown file foo.md into a component <Bar />? Will props need to be used for this? Can MDX handle such scenarios effectively? Your help is greatly appreciated! ...

Retrieve HTML form data or an object within the getServerSideProps() function in NEXTJS

How can I submit form data from a NextJS page to another page with server-side rendering? The function getServerSideProps() on the receiving page requires these form data to make an API call. I considered using localStorage/sessionStorage to store the da ...

It appears that my React component is not being rerendered even after using componentDidMount and setState to update it

/*I have successfully fetched data and set it to state, however, when attempting to generate an array of jsx items for display, the array appears empty and nothing is rendering. I tried hardcoding and it worked. I also logged the data which showed that th ...

There was a problem with the WebSocket handshake: the response header value for 'Sec-WebSocket-Protocol' did not match any of the values sent

I've encountered an issue with my React project that involves streaming live video through a WebSocket. Whenever the camera firmware is updated, I face an error in establishing the WebSocket connection. Here's how I initiate the WebSocket: wsRe ...

Height specification in Tailwind Grid

Hi there! I'm currently working on implementing a grid system in NextJS using Tailwind CSS. However, I've hit a roadblock when it comes to automatically sizing the grids to fit the parent element. Let me illustrate my issue with two images below ...