Search code examples
reactjsredux

Seeing the previous details in a component


I have a component that, dispatches an action that calls an API that updates a redux store and displays the updated store via a selector

The trouble I'm having is that when I navigate away from the component and comeback, the previous information is in the UI for a second before it updates to the new information

"use client";
import React, { useState, useEffect, useCallback } from "react";

import { useAppDispatch, useAppSelector } from "@/lib/hooks/store.hooks";

import styles from "@/styles/components/_detail.module.scss";
import {
  getAlbum,
  selectAlbumDetail,
} from "@/lib/features/music/musicSlice";

import { AlbumDetail } from "@/shared/interfaces/music";

const initialAlbumDetail: AlbumDetail = {
  artists: [],
  image: "",
  name: "",
  release_date: "",
  spotify_link: "",
  tracks: [""],
  category: "",
};

const AlbumDetails = ({ params: { id } }: { params: { id: string } }) => {

const dispatch = useAppDispatch();
const [albumDetails, setAlbumDetails] =
    useState<AlbumDetail>(initialAlbumDetail);

const album: AlbumDetail = useAppSelector(selectAlbumDetail);

const [isFetching, setIsFetching] = useState(true);

const fetchAlbumDetails = useCallback(() => {
    setIsFetching(true);
    dispatch(getAlbum(id));
  }, [dispatch, id]);

  useEffect(() => {
    setAlbumDetails(initialAlbumDetail);
    fetchAlbumDetails();
  }, [fetchAlbumDetails]);

  useEffect(() => {
    if (album) {
      setAlbumDetails(album);
      setIsFetching(false);
    }
  }, [album]);

  if (isFetching) return <div>Loading...</div>;

  return (
    <>
      <div>{albumDetails.name}</div>
    </>
  );
};

export default AlbumDetails;

Solution

  • the best way I found to solve this was to create a redux action/reducer to clear the details

    clearAlbumDetails: create.reducer((state) => {
          state.selectedAlbum = {} as AlbumDetail;
     }),
    

    And then dispatch the action on the page that I navigate to when leaving this one.