Search code examples
reactjsreact-state

Data is not filtering in props. Showing passdata.map is not a function


I am trying to make a to do list. MY app take a data successfully. But when I want to delete a data from the list. it is showing typeerror: passdata.map is not a function. I am just learning react and I can not figure out where the problem is. N:B: My code is in between two components.

import React, { useState } from "react";
import { OutputData } from "./OutputData";

export const Form = () => {
  const [data, setData] = useState("");
  const [val, setVal] = useState([]);

  const changed = (event) => {
    setData(event.target.value);
  };
  const clicked = () => {
    setVal((oldVal) => {
      return [...oldVal, data];
    });
    setData(" ");
    
  };
  const del = (id)=>{
     setVal((newVal)=>{
      return newVal.filter((val,index)=>{
        return id !== index;
      });
     });
     setVal("");
  }
  

  return (
    <div>
      <div>
        <h1>To Do List</h1>
        <input type="text" onChange={changed} />
        <button onClick={clicked}>
          <span>+</span>
        </button>
      </div>
      <div>
        <OutputData passData={val} del={del}></OutputData>
      </div>
    </div>
  );
};

My Second Component Here:

import React from 'react'

export const OutputData = ({passData,index,del}) => {
  return (
    <div>
        {
            passData.map((passData,index)=>{
                return(
                    <div className='lidiv' key={index}>
                        <li>{passData}</li>
                        <button onClick={() => del(index)}>Delete</button>
                    </div>
                )
            })
        }
    </div>
  )
}

I want to know why is this happened & How to solve this problem


Solution

  • You are calling setVal(""), which is changing the data type from an array to a string.