1
resposta

o meu ta dado esse erro aqui olha

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. at Object.throwInvalidHookError (react-dom.development.js:14906:1) at useContext (react.development.js:1504:1) at useStoreRef (recoil.js:3696:1) at useSetRecoilState (recoil.js:4854:1) at onEventDragFinish (index.tsx:51:1) at $d936bbeb8e3b329f$export$fd46f924699b0eb4 (draggingGeneral.ts:72:1) at HTMLDocument.onMouseUp (EventButton.tsx:277:1) throwInvalidHookError @ react-dom.development.js:14906 useContext @ react.development.js:1504 useStoreRef @ recoil.js:3696 useSetRecoilState @ recoil.js:4854 onEventDragFinish @ index.tsx:51 $d936bbeb8e3b329f$export$fd46f924699b0eb4 @ draggingGeneral.ts:72 onMouseUp @ EventButton.tsx:277 WebSocketClient.js:16 WebSocket connection to 'wss://3000-gabrielsant-typescripta-77lhveu5dyf.ws-us42.gitpod.io:3000/ws' failed: WebSocketClient @ WebSocketClient.js:16 initSocket @ socket.js:24 ./node_modules/webpack-dev-server/client/index.js?protocol=ws%3A&hostname=0.0.0.0&port=3000&pathname=%2Fws&logging=none&reconnect=10 @ index.js:273 options.factory @ react refresh:6 webpack_require @ bootstrap:24 (anonymous) @ startup:5 (anonymous) @ startup:7

meu codigo


import React from 'react'
import style from './Calendario.module.scss';
import ptBR from './localizacao/ptBR.json'
import Kalend, { CalendarEvent, CalendarView, OnEventDragFinish } from 'kalend'
import 'kalend/dist/styles/index.css';
import { useRecoilValue } from 'recoil';
import { listaDeEventosState } from '../../state/atom';
import {useSetRecoilState} from "recoil"
import { IEvento } from '../../interfaces/IEvento';


interface IKalendEvento {
  id?: number
  startAt: string
  endAt: string
  summary: string
  color: string
}

const Calendario: React.FC = () => {

  const eventosKalend = new Map<string, IKalendEvento[]>();
  const eventos = useRecoilValue(listaDeEventosState);

  eventos.forEach(evento => {
    const chave = evento.inicio.toISOString().slice(0, 10)
    if (!eventosKalend.has(chave)) {
      eventosKalend.set(chave, [])
    }
    eventosKalend.get(chave)?.push({
      id: evento.id,
      startAt: evento.inicio.toISOString(),
      endAt: evento.fim.toISOString(),
      summary: evento.descricao,
      color: 'blue'
    })
  })

  const onEventDragFinish: OnEventDragFinish = (
    kalendEventoInalterado : CalendarEvent,
    kalendEventoAtualizado: CalendarEvent,

  ) => {
    const evento = eventos.find(evento => evento.descricao === kalendEventoAtualizado.summary)
    if(evento){
      const eventoAtualizado = { ...evento }
      eventoAtualizado.inicio = new Date(kalendEventoAtualizado.startAt)
      eventoAtualizado.fim = new Date(kalendEventoAtualizado.endAt)

      const setListaDeEventos = useSetRecoilState<IEvento[]>(listaDeEventosState)
      setListaDeEventos(listaAntiga => {

        const i  = listaAntiga.findIndex(e => e.id ===  evento.id )
        return [...listaAntiga.slice(0,i) , eventoAtualizado, ...listaAntiga.slice(i+1)]
      })
    }
  };

  return (
    <div className={style.Container}>
      <Kalend
        events={Object.fromEntries(eventosKalend)}
        initialDate={new Date().toISOString()}
        hourHeight={60}
        initialView={CalendarView.WEEK}
        timeFormat={'24'}
        weekDayStart={'Monday'}
        calendarIDsHidden={['work']}
        language={'customLanguage'}
        customLanguage={ptBR}
        onEventDragFinish={onEventDragFinish}
      />
    </div>
  );
}

export default Calendario
1 resposta

Salve, Gabriel.

Dentro da sua função onEventDragFinish você está chamando o recoil const setListaDeEventos = useSetRecoilState<IEvento[]>(listaDeEventosState).

E hooks precisam ser chamados apenas no nível superior.

Basta você ajustar isso, mais ou menos assim:

import React from 'react'
import style from './Calendario.module.scss';
import ptBR from './localizacao/ptBR.json'
import Kalend, { CalendarEvent, CalendarView, OnEventDragFinish } from 'kalend'
import 'kalend/dist/styles/index.css';
import { useRecoilValue } from 'recoil';
import { listaDeEventosState } from '../../state/atom';
import {useSetRecoilState} from "recoil"
import { IEvento } from '../../interfaces/IEvento';


interface IKalendEvento {
  id?: number
  startAt: string
  endAt: string
  summary: string
  color: string
}

const Calendario: React.FC = () => {

  const eventosKalend = new Map<string, IKalendEvento[]>();
  const eventos = useRecoilValue(listaDeEventosState);
  const setListaDeEventos = useSetRecoilState<IEvento[]>(listaDeEventosState)

  eventos.forEach(evento => {
    const chave = evento.inicio.toISOString().slice(0, 10)
    if (!eventosKalend.has(chave)) {
      eventosKalend.set(chave, [])
    }
    eventosKalend.get(chave)?.push({
      id: evento.id,
      startAt: evento.inicio.toISOString(),
      endAt: evento.fim.toISOString(),
      summary: evento.descricao,
      color: 'blue'
    })
  })

  const onEventDragFinish: OnEventDragFinish = (
    kalendEventoInalterado : CalendarEvent,
    kalendEventoAtualizado: CalendarEvent,

  ) => {
    const evento = eventos.find(evento => evento.descricao === kalendEventoAtualizado.summary)
    if(evento){
      const eventoAtualizado = { ...evento }
      eventoAtualizado.inicio = new Date(kalendEventoAtualizado.startAt)
      eventoAtualizado.fim = new Date(kalendEventoAtualizado.endAt)

      setListaDeEventos(listaAntiga => {

        const i  = listaAntiga.findIndex(e => e.id ===  evento.id )
        return [...listaAntiga.slice(0,i) , eventoAtualizado, ...listaAntiga.slice(i+1)]
      })
    }
  };

  return (
    <div className={style.Container}>
      <Kalend
        events={Object.fromEntries(eventosKalend)}
        initialDate={new Date().toISOString()}
        hourHeight={60}
        initialView={CalendarView.WEEK}
        timeFormat={'24'}
        weekDayStart={'Monday'}
        calendarIDsHidden={['work']}
        language={'customLanguage'}
        customLanguage={ptBR}
        onEventDragFinish={onEventDragFinish}
      />
    </div>
  );
}

export default Calendario