Reducer 400 bed request on refresh page how can i solve - reactjs

const DashboardPage = (props) => {
const userData = useSelector((state) => state.userDataReducer.user_record_reducer)
console.log('userdata', userData);
const adm_id = userData.adm_id
const [vistLoader, setVisitLoader] = useState(false)
const drid = localStorage.getItem('drId')
const [dashboard, setDashboard] = useState({})
const [collapsed,setCollapased] = useState(false);
const mr = userData.mrno
useEffect(()=>{
setVisitLoader(true)
const dashboard = getPatientDashboard({mr,drid}).then(res =>{
setDashboard(res)
setTimeout(()=>{
setVisitLoader(false)
}, 500)
}).catch(err =>{
console.log('err',err);
})
},[])

Related

useState isn't updating

I'm fetching an api and want to change useState when the api is returned. However, it simply isn't updating.
Any suggestions?
const fictionApi = "http://localhost:3000/fiction"
const nonFictionApi = "http://localhost:3000/non_fiction"
const [fictionData, setFictionData] = useState(null)
const db = async (url) => {
const res = await fetch(url)
const data = await res.json()
setFictionData(data)
console.log(data.genre)
}
useEffect(() => {
const db = async (url) => {
const res = await fetch(url)
const data = await res.json()
setFictionData(data)
console.log(fictionData)
}
db(fictionApi)
}, [])
I think there is something strange with your syntax.
Something like this should work :
const fictionApi = "http://localhost:3000/fiction"
const nonFictionApi = "http://localhost:3000/non_fiction"
export default function Page () {
const [fictionData, setFictionData] = useState(null);
const [url, setUrl] = useState(fictionApi); // ';' very important
useEffect(() => {
(async () => {
const res = await fetch(url)
const data = await res.json()
setFictionData(data)
})() //Self calling async function
}, [])
}
Moreover, setState is an async process so :
const [fictionData, setFictionData] = useState(null);
setFictionData(true)
console.log(fictionData) //null
So you can use a useEffect to check state :
const [fictionData, setFictionData] = useState(null);
useEffect(()=>{
console.log(fictionData) //true
},[fictionData])
setFictionData(true)

useEffect not refreshing or Triggering on Adding New Friends

const {Account,flag,setfriends} = useContext(AccountContext);
const [text,settext] = useState('');
useEffect(()=>{
const get = async() => {
// if(friends.length !== 0) return
const res = await getFriends(Account._id);
const data = res.data?.friends;
const filterData = data.filter(ele=>ele.name.toLowerCase().includes(text.toLowerCase()))
setfriends(filterData);
}
get(); //want to refetch data when new friend added
// eslint-disable-next-line
},[flag,text]);
//User.jsx
const {setperson} = useContext(PersonContext);
const {Account,flag,setflag} = useContext(AccountContext);
const add = async() => {
const data = {
user:userinfo,
info,
}
await addFriend(data);
setflag(!flag); **changing context flag which will recall upper useEffect but not callingi it
};
plese help me to Recall the upper useEffect it is not calling again when context flag changes
// AccountContext.jsx
import React,{createContext, useState,useRef,useEffect} from 'react'
import {io} from 'socket.io-client';
export const AccountContext = createContext(null);
const AccountProvider = ({children}) => {
const socket = useRef();
const [Account,setAccount] = useState();
const [activeUsers,setactiveUsers] = useState([]);
const [flag,setflag] = useState(false);
const [friends,setfriends] = useState([]);
useEffect(()=>{
socket.current = io('ws://localhost:8000')
},[])
return (
<AccountContext.Provider value={{Account,setAccount,activeUsers,setactiveUsers,flag,setflag,socket,friends,setfriends}}>{children}</AccountContext.Provider>
)
}
export default AccountProvider
These is Account Provider where i have saved freinds list

How to pass variable to hook in React?

I am trying to pass some custom metadata to my firebase firestore, I believe I must pass the metadata I grabbed in my component up to the hook but am unsure how to do so,
my component:
const UploadForm = () => {
const [file, setFile] = useState(null);
const [error, setError] = useState(null);
const [metadata, setMetadata] = useState(null);
const types = ['image/png', 'image/jpeg'];
const changeHandler = (e) => {
let selected = e.target.files[0];
if (selected && types.includes(selected.type)) {
setFile(selected);
setError('');
const pieceName = document.getElementById("pieceName").value;
const pieceDescription = document.getElementById("pieceDescription").value;
const newMetadata = {
customMetaData: {
artName: pieceName,
artDescription: pieceDescription
}
};
setMetadata(newMetadata);
...
export default UploadForm;
& my hook:
const useStorage = (file, metadata) => {
const [progress, setProgress] = useState(0);
const [error, setError] = useState(null);
const [url, setUrl] = useState(null);
useEffect(() => {
// references
const storageRef = projectStorage.ref(file.name);
const collectionRef = projectFirestore.collection('images');
storageRef.put(file).on('state_changed', (snap) => {
let percentage = (snap.bytesTransferred / snap.totalBytes) * 100;
setProgress(percentage);
}, (err) => {
setError(err);
}, async () => {
const url = await storageRef.getDownloadURL();
const createdAt = timestamp();
collectionRef.add({ url, createdAt, metadata });
setUrl(url);
});
}, [file, metadata]);
return { progress, url, error };
}
export default useStorage;
I am able to upload to Firebase Storage/firestore no problem but don't know how to feed this extra metadata.
To change the metada just call the updateMetadata on the ref:
const useStorage = (file, metadata) => {
const [progress, setProgress] = useState(0);
const [error, setError] = useState(null);
const [url, setUrl] = useState(null);
useEffect(() => {
// references
const storageRef = projectStorage.ref(file.name);
const collectionRef = projectFirestore.collection('images');
storageRef.put(file).on('state_changed', (snap) => {
let percentage = (snap.bytesTransferred / snap.totalBytes) * 100;
setProgress(percentage);
}, (err) => {
setError(err);
}, async () => {
await storageRef.updateMetadata(metadata)
const url = await storageRef.getDownloadURL();
const createdAt = timestamp();
collectionRef.add({ url, createdAt, metadata });
setUrl(url);
});
}, [file, metadata]);
return { progress, url, error };
}
export default useStorage;
You can read more about it here.

Infinite loop after adding a dependency

When I'm adding dependency fetchData, my app becomes an infinite loop.
What am I doing wrong?
React Hook useEffect has a missing dependency: 'fetchData'. Either include it or remove the dependency array
const [films, setFilms] = useState([]);
const [page, setPage] = useState(1);
const [isLoad, setIsLoad] = useState(false);
const incrementPage = () => {
setPage(page + 1);
};
const fetchData = async () => {
setIsLoad(true);
const response = await fetch(
`${baseURL}movie/popular?api_key=${API_KEY}&language=en-US&page=${page}`
).then((res) => res.json());
setFilms([...films, ...response.results]);
setIsLoad(false);
incrementPage();
};
useEffect(() => {
fetchData();
}, []);
I would place the contents of fetchData into the useEffect instead.
const [films, setFilms] = useState([]);
const [page, setPage] = useState(1);
const [isLoad, setIsLoad] = useState(false);
const incrementPage = () => {
setPage(page + 1);
};
useEffect(() => {
setIsLoad(true);
const response = await fetch(
`${baseURL}movie/popular?api_key=${API_KEY}&language=en-US&page=${page}`
).then((res) => res.json());
setFilms([...films, ...response.results]);
setIsLoad(false);
incrementPage();
}, [setIsLoad, page, setFilms, setIsLoad, incrementPage]);
Then it will automatically fetch new data if 'page' is changed.

Spotify player SDK in react

I am trying to implement Spotify player SDK in my react app. But I do not know it is giving me an error that Spotify is undefined. I am trying to implement the script in the useEffect hook in this context file.
This is my context file and trying to set up player SDK in it. Thanks in advance.
import React,{ createContext, useState,useEffect } from 'react'
import { myPlaylist, fetchAnything } from "../../api-fetching/api-fetching"
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split("&")
.reduce(function(initial, item) {
if (item) {
var parts = item.split("=");
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = "";
export const MainContext = createContext();
const MainContextProvider = (props) => {
const authEndPoint = 'https://accounts.spotify.com/authorize?';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = "5c4e46e8acf24w794ru325qi535fw5325hsakf22be91378ff14";
let redirectUri = "";
if(process.env.NODE_ENV === "development") {
redirectUri += "http://localhost:3000/";
}
const scopes = [
"streaming", "user-read-email", "user-read-private",
"user-read-currently-playing",
"user-read-playback-state",
"user-library-read",
"playlist-read-collaborative",
"playlist-read-private"
];
const [token, setToken] = useState(null);
const [scriptLoading, setScriptLoading] = useState(true);
const [currentUser, setCurrentUser] = useState(null);
const [discover, setDiscover] = useState(null);
const [discoverPlaylist, setDiscoverPlaylist] = useState(null);
const [discoverPlaylistTracks, setDiscoverPlaylistTracks] = useState(null);
const [userPlaylist, setUserPlaylist] = useState(null);
const [ userPlaylistTracks ,setUserPlaylistTracks] = useState(null);
const [artistInfo, setArtistInfo] = useState(null);
const [albumTracks, setAlbumTracks] = useState(null);
const [newReleases, setNewReleases] = useState(null);
const [newReleasesTracks, setNewReleasesTracks] = useState(null);
const [searchResult, setSearchResult] = useState(null);
const [searchValue, setSearchValue] = useState("");
const [playlistTracks, setPlaylistTracks] = useState(null);
useEffect(() => {
let _token = hash.access_token;
setToken(_token);
fetchAnything(token, "https://api.spotify.com/v1/me", setCurrentUser);
if(scriptLoading){
const script = document.createElement("script");
script.src = "https://sdk.scdn.co/spotify-player.js";
script.async = true;
script.defer = true;
document.body.appendChild(script);
setScriptLoading(false);
}
window.onSpotifyWebPlaybackSDKReady = () => {
const player = new Spotify.Player({
name: 'Web Playback SDK Quick Start Player',
getOAuthToken: cb => { cb(token); }
});
// Error handling
player.addListener('initialization_error', ({ message }) => { console.error(message); });
player.addListener('authentication_error', ({ message }) => { console.error(message); });
player.addListener('account_error', ({ message }) => { console.error(message); });
player.addListener('playback_error', ({ message }) => { console.error(message); });
// Playback status updates
player.addListener('player_state_changed', state => { console.log(state); });
// Ready
player.addListener('ready', ({ device_id }) => {
console.log('Ready with Device ID', device_id);
});
// Not Ready
player.addListener('not_ready', ({ device_id }) => {
console.log('Device ID has gone offline', device_id);
});
// Connect to the player!
player.connect();
};
}, [token])
useEffect(() => {
if(currentUser){
myPlaylist(token, setUserPlaylist, currentUser.id);
}
}, [currentUser, token])
return (
<MainContext.Provider
value={{ currentUser,playlistTracks, setPlaylistTracks ,searchValue, setSearchValue,searchResult, setSearchResult,newReleasesTracks, setNewReleasesTracks ,newReleases, setNewReleases ,albumTracks, setAlbumTracks,artistInfo, setArtistInfo,discoverPlaylistTracks, setDiscoverPlaylistTracks,userPlaylistTracks, setUserPlaylistTracks, userPlaylist,discoverPlaylist,setDiscoverPlaylist,discover,setDiscover, token,setToken, authEndPoint, clientId, redirectUri, scopes }}>
{props.children}
</MainContext.Provider>
)
}
export default MainContextProvider
You must refer to the Player through a global object:
window.onSpotifyWebPlaybackSDKReady = () => {
const player = new window.Spotify.Player({
name: "Carly Rae Jepsen Player",
getOAuthToken: (callback) => {
callback("access token here");
},
volume: 0.5,
});
};

Resources