1

I'm trying to get data API from star wars website with react project and here's my code:

const Form = (props) => {
  const [search, setSearch] = useState("people");
  const [searchID, setSearchID] = useState(1);

  const [responseData, setResponseData] = useState({});

  useEffect(() => {
    buttonAPI();
    setSearch(props.type);
  }, [props.type]);

  const buttonAPI = () => {
    axios
      .get(`https://swapi.dev/api/${props.type}/`)
      .then((res) => {
        setResponseData(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const onSubmit = (e) => {
    e.preventDefault();
    navigate(`/${search}/${searchID}`);
  };

  return (
    <div className="container" style={pageStyle}>
      <form onSubmit={onSubmit}>
  .
  .
  .

)

I'm getting this error while trying to add props.setSearch(props.type); into useEffect

Here is my github for this project:

https://github.com/nathannewyen/reactjs-practice/tree/master/luke-api

3
  • 1
    setSearch is not passed as a prop to the component, in fact is available to the component due to the useState() hook. Just call setSearch(props.type) and it should work. Also remember to pass an array in order to run the effect only when a relevant prop or state property is updated: reactjs.org/docs/… Commented Jul 13, 2020 at 23:01
  • Yea I tried your way and just edited my code but some how props.type is undefined in my axios Commented Jul 13, 2020 at 23:07
  • You actually have to pass the type prop to the Form component and make sure is a function. Something like this: <Form type={someFunction} /> Just saw below that the comment by @yash addresses the same thing :D Commented Jul 13, 2020 at 23:26

1 Answer 1

1

From your App.jsx:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Info from "./components/Info";
import Form from "./components/Form";

function App() {
  return (
    <div className="App">
      <Form />
      <Info />
    </div>
  );
}

export default App;

You pass nothing to Form component, so the props is empty and you cannot call a function that not exists.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I pass it into Form components?
simple :) <Form type={SOMETHING_YOU_WANT_TO_PASS} />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.