Home > database >  React JS : Uncaught TypeError: keeps.map is not a function
React JS : Uncaught TypeError: keeps.map is not a function

Time:11-05

import React, { useState } from "react";
import Input from "./components/Input";
import Keep from './components/Keep'

export default function App() {
  const [keeps, setKeeps] = useState(['go','do','make','sleep',])
  let keepsList = keeps.map((keep, id)=>{return <Keep value={keep} key={id} />})
  const onSubmit = (e) => {
    setKeeps(...keeps, e)
    console.log(keeps)
  }
  return (
    <>
    <div className="App">
      <div className="Logo">N13G's Keeps</div>
      <Input onSubmit={onSubmit}/>
      <div className="KLmain">
        { keepsList }
      </div>
    </div>
    </>
  )
}

My kind of analog of Google Keeps doesn't work. It returns an error in a console (keeps.map is not a function).
There's also my Input

import React from "react";

function Input ({onSubmit}) {
 const handleSubmit = (e) => {
  e.preventDefault()
  onSubmit(e.target.value)
 }
 return (
 <>
  <form className="Icont" onSubmit={handleSubmit}>
   <input type="text" className="Iinput"/>
   <input type="submit" className="Ibut" placeholder="Add" value={"Add"}/>
  </form>
 </> )
}

export default Input

I digged first 3 pages of Google search and find nothing. I tried to fix this error by classes, but maybe it's a React bug.

CodePudding user response:

Try this inside your onSubmit method:

setKeeps([...keeps, e])

because you have already set keeps as an array. So to set value in setKeeps you have to pass an array and to add value into array you can do like this [...keeps, e]

CodePudding user response:

I recommend you use setKeeps(prev => [...prev, e]) instead of setKeeps(...keeps, e). And also use the keeps.map(... inside the div tag. I hope this helped you!

  • Related