Home > Blockchain >  react-Post method only adding new "id" but data inside body tag not getting added
react-Post method only adding new "id" but data inside body tag not getting added

Time:12-29

I can see correct data added inside body tag POST method but in end url only id is getting added. am i doing something wrong?

following is the output I am getting, data should like id:3, but in subsequent Post's only id is getting added.

{
id: "3",
title: "Greek Salad",
ingredients: [
"1 Onion",
"1 Block of Feta",
"Olives",
"Tomatoes",
"Olive Oil"
],
method: "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Esse minima ex rem quis similique eum ratione quaerat, voluptas molestias ut repudiandae delectus voluptates. Eius esse at tenetur ab accusamus excepturi?",
cookingTime: "35 minutes"
},
{
id: "lXOYU8C"
},
{
id: "IacXVJs"
},

I am using following hook for get& post method.

const useFetch = (url, method="GET") => {
  const [data, setData] = useState(null);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState(null);
  const [option, setOptions] = useState(null)

  const PostData = (info)=>{

    setOptions({
      method:"POST",
      header:{
        "Content-Type":"application/json"
      },
      body : JSON.stringify(info)
    })
  }

  const fetchData = async (fetchOptions) => {
    console.log("fetchOptions :",fetchOptions)
    try {
      setIsPending(true);

      const response = await fetch(url,{...fetchOptions});
      const databyresponse = await response.json();

      setIsPending(false);
      setData(databyresponse);
      setError(null);
    } catch (e) {
      setIsPending(false);

      console.log("error", e);

      setError(e);
    }
  };

  useEffect(() => {

    if(method == "GET"){
      
      fetchData();
    }
    if(method == "POST" && option){

      fetchData(option);

    }
  }, [url,option,method]);

  return { data, isPending, error, PostData };
};

export default useFetch;

and this is how i am calling my post method.

const  {data, isPending, error, PostData } = useFetch("http://localhost:3000/recipes", "POST");

 
  const [input, setInput] = useState({
    title: "",
    cookingTime: "",
    method: "",
  });
  const [ingtext, setIngtext] = useState("");
  const [ingredients, setIngredients] = useState([]);

  const IngredientInput = useRef(null);

  const onSubmithandler = (e) => {
    console.log("submitted");
    e.preventDefault();
    console.log({input,ingredients})
   let title = input.title;
   let cookingTime = input.cookingTime;
   let method = input.method;

    PostData({title,cookingTime,method,ingredients})
  };

CodePudding user response:

It should have been:

setOptions({
  methods:"POST",
   header: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(info)
})

the missing s in methods was the culprit.

  • Related