javascriptreactjsparameter-passingslice

My userId is not passing from the page to the slice, but the form is. I am not sure why it is not passing correctly


postSlice.js

   createPost: builder.mutation({
      query: ({ usersId, ...form }) => ({
        url: `/createPost/user/${usersId}`,
        method: "POST",
        body: { form, userId: usersId },
        // responseHandler: (response) => response.text(),
      }),
      invalidatesTags: ["User"],
    })

post.jsx

  const [createPost] = useCreatePostMutation();
  const state = useSelector((state) => state);
  const usersId = window.sessionStorage.getItem("User");

  const [form, setForm] = useState({
    title: "",
    content: "",
  });

  const [message, setMessage] = useState("");

  const update = (e) => {
    setForm((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  };

  const submit = async (e) => {
    e.preventDefault();
    setMessage("");
    try {
      if (!form.title || !form.content) {
        setMessage("Please fill in all required fields.");
        return;
      }

      let response = false;

      response = await createPost(form, usersId).unwrap();
      console.log(response);

      if (response) {
        setMessage("Post successful!");
        navigate("/");
      }
    } catch (error) {
      setMessage("Post failed. Please try again.");
    }
  };

Using dev tools, I can see that the form is being passed correctly, the usersId is coming back as undefined in the slice. It is appearing in the submit function, but it is not being passed. Not sure why??


Solution

  • Your argument is not being passed correctly because the createPost mutation expects an object but you're passing the arguments as individual values. You should modify your code as follows:

      const [createPost] = useCreatePostMutation();
      const state = useSelector((state) => state);
      const usersId = window.sessionStorage.getItem("User");
    
      const [form, setForm] = useState({
        title: "",
        content: "",
      });
    
      const [message, setMessage] = useState("");
    
      const update = (e) => {
        setForm((prev) => ({
          ...prev,
          [e.target.name]: e.target.value,
        }));
      };
    
      const submit = async (e) => {
        e.preventDefault();
        setMessage("");
        try {
          if (!form.title || !form.content) {
            setMessage("Please fill in all required fields.");
            return;
          }
    
          let response = false;
    
          response = await createPost({form, usersId}).unwrap();
          console.log(response);
    
          if (response) {
            setMessage("Post successful!");
            navigate("/");
          }
        } catch (error) {
          setMessage("Post failed. Please try again.");
        }
      };
    

    This should pass correct argument to your mutation