1

Ошибка при передаче стейта в value провайдера (подсвечивается "state") <AppContext.Provider value={{ state, dispatch }}>

Не могу разобраться как исправить, помогите(

Сама ошибка

Type '{ state: any; dispatch: React.Dispatch; }' is not assignable to type '{ todos: { title: string; }[]; }'. Object literal may only specify known properties, and 'state' does not exist in type '{ todos: { title: string; }[]; }'.ts(2322) index.d.ts(325, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<{ todos: { title: string; }[]; }>'

import React, { useContext, useReducer, useState, createContext } from 'react'

const defaultState = {
  todos: []
}

const AppContext = createContext(defaultState)
const ADD_TODO = 'ADD_TODO', DELETE_TODO = 'DELETE_TODO'

const reducer = (state: any, action: any) => {
  const { type, payload } = action
  switch (type) {
    case ADD_TODO:
      return { todos: [payload, ...state.todos] }
    case DELETE_TODO:
      return { todos: state.todos.filter((todo: any) => todo.id !== payload) }
    default:
      return state
  }
}

const TodoForm = () => {
  const [title, setTitle] = useState('')
  const { dispatch }: any = useContext(AppContext)

  const handleChange = ({ target: { value } }: any) => {
    setTitle(value)
  }

  const handleClick = () => {
    setTitle('')
    dispatch({
      type: ADD_TODO,
      payload: {
        id: crypto.randomUUID(),
        title
      }
    })
  }

  const handleEnter = (e: any) => {
    if (e.key === 'Enter') {
      handleClick();
    }
  }

  return (
    <div>
      <input
        type="text"
        placeholder='enter title'
        onChange={handleChange}
        value={title}
        onKeyDown={handleEnter}
      />
      <button onClick={handleClick}>add</button>
    </div>
  );
}

const TodoList = () => {
  const { state: { todos }, dispatch }: any = useContext(AppContext)

  const handleDeletet = (id: any) => () => {
    dispatch({
      type: DELETE_TODO,
      payload: id
    })
  }

  return (
    <ul>
      {todos.map((todo: any) => (
        <li key={todo.id}>
          {todo.title}
          <button onClick={handleDeletet(todo.id)}>X</button>
        </li>
      ))}
    </ul>
  )
}

const App = () => {
  const [state, dispatch] = useReducer(reducer, defaultState)

  return (
    <div>
      <AppContext.Provider value={{ state, dispatch }}>
        <TodoForm />
        <TodoList />
      </AppContext.Provider>
    </div>)
}

export default App

2 ответа 2

1

Помогло добавление интерфейса для контекста

interface AppContextIntreface {
  state: any,
  dispatch: any
}

const AppContext = createContext<AppContextIntreface>({
  state: defaultState,
  dispatch: () => null
})
0

Как минимум, вместо

const AppContext = createContext(defaultState)

нужно написать:

const AppContext = createContext({
  state: defaultState,
  dispatch: () => null
});
1
  • Уже лучше, теперь только на диспатч ругается (property) dispatch: () => null Type 'Dispatch<any>' is not assignable to type '() => null'.ts(2322) app.tsx(9, 3): The expected type comes from property 'dispatch' which is declared here on type '{ state: { todos: never[]; }; dispatch: () => null; } '
    – sonochiwa
    23 апр 2022 в 15:10

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.