Why should I click twice on Button to get data from useSWR ( NextJS )?

52 Views Asked by At

I have a Button component where I get data from my backend API using useSWR.

This is my button:


interface IButtonProps {
  address: string;
}

const AddressCheckButton = ({ address }: IButtonProps) => {
  const [shouldFetch, setShouldFetch] = useState(false);
  const dispatch = useDispatch();
  const router = useRouter();
  const url = process.env.NEXT_PUBLIC_API_URL;

  const { data: userLocation, error } = useSWR(
    shouldFetch ? url + address : null,
    (url) => fetcher(url, headers)
  );

  const handleValidate = () => {
    fetchData();
  };

  const fetchData = () => {
    try {
      setShouldFetch(true);
      if (userLocation) {
        const { zipCode, city, street, houseNumber } = userLocation;
        console.log(userLocation);

        if (zipCode && city && street && houseNumber) {
          dispatch(updateAddressId({ address }));
          dispatch(updateSolarLocation({ zipCode, city, street, houseNumber }));
          setShouldFetch(false);
          router.push(`/${address}`);
        }
      } else {
        console.log("error");
      }
    } catch (error) {
      setShouldFetch(false);
      console.log(error);
    }
  };
  return (
    <>
      <Button
        text="Code überprüfen"
        onClick={handleValidate}
        type={"ternary"}
      />
      {error?.length > 0 ? (
        <div className={styles.error}>
          <p>{error}</p>
        </div>
      ) : null}
    </>
  );
};

The problem is when I click ( first click ) it logs an error' because userLocationisundefined while the useSWR is fetching the data. The button code is synchronous and the useSWR is asynchronous, how to wait foruserLocationto be available to run theif` code?

0

There are 0 best solutions below