#useParams causing issue in Reducer Fetch

5 messages · Page 1 of 1 (latest)

cobalt grail
#

I have a reducer that contains a function that creates a POST fetch request, and am able to use this function just fine on certain pages, but on a page where useParams is being used, it will change the api of the fetch, resulting in a 404 error:

the correct fetch should be : fetch("api/update-cart", ...)

i have a button on a test page which runs this function when clicks. the route for the page does not use useParams (route /test) - and it all works fine

but on a page which does use useParams (route /details/:productId), the fetch in my reducer seems to be using the useParams and fetching from /details/api/update-cart rather than just "api/update-cart", so I get a a 404.
Response {type: 'basic', url: 'http://localhost:3000/details/api/update-cart', redirected: false, status: 404, ok: false, …}

any ideas how to get it to not dynamically render the fetch url?

wide elbow
#

if your reducer function is generating the fetch URL, then the page using useParams is taking the params from it maybe? Can you share your reducer function to investigate?

cobalt grail
#

export const CartContext = createContext();

const initialCartState = {};

const reducer = (cartState, action) => {
  const cartCode = sessionStorage.getItem("cartCode");

  switch (action.type) {
    case "create-cart":
      {
        fetch("api/create-new-cart", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            [[action.selectedItemId._id]]: {
              ...action.selectedItemId,
              quantity: 1,
            },
          }),
        })
          .then((res) => res.json())
          .then((data) => {
            sessionStorage.setItem("cartCode", data.data.cartCode);
        
          });
      }
      return {
        cartState,
      };

    
    default: {
      throw new Error(`Unrecognized action: ${action.type}`);
    }
  }
};

export const CartProvider = ({ children }) => {
  const [cartState, dispatch] = useReducer(reducer, initialCartState);

  const createCart = (data) => {
    dispatch({
      type: "create-cart",
      selectedItemId: data,
    });
  };

  
  return (
    <CartContext.Provider
      value={{
        cartState,
        actions: {
          createCart,
        },
      }}
    >
      {children}
    </CartContext.Provider>
  );
};
wide elbow
#

How is your api url grabbed in your fetch? is it just taking it from the current url?

#

if its a static url, then define a baseURL above it and then fetch using that instead

const baseURL = "http://localhost:3000/api/create-new-cart";

fetch(baseURL, {...})