wondering how this could happen when this get call API twice. I'am using nextjs with typescript and using and design.
Below my code
const EditRoles = () => {
const router = useRouter();
const router = useRouter();
const { id } = router.query;
const [detail, setDetail] = useState();
const [rolePermission, setRolePermission] = useState([]);
const [pagination, setPagination] = useState<Params>({
page: 1,
row: 10,
});
const [loading, setLoading] = useState(false);
const [nextPage, setNextPage] = useState(0);
const getRolePermission = async (payload: { page?: number; row?: number; search?: string }) => {
if (id) {
setLoading(true);
const res = await httpService
.get(`${apiUrl.user}/v1/role-permission/${id}`, { params: payload })
.then((resp) => resp);
const rps = await res.data;
setLoading(false);
const roleP = rps.data.map((rp) => {
return { ...rp };
});
setRolePermission(rps.page === 1 ? roleP : [...rolePermission, ...roleP]);
setNextPage(rps.nextPage);
setPagination({ ...pagination, page: pagination.page + 1 });
console.log('this next page: ', rps.nextPage);
}
};
useEffect(() => {
getDetailRole();
getRolePermission({
...pagination,
});
form.setFieldsValue({
name: detail,
permissions: rolePermission,
});
}, [id, form, detail]);
return (
// ... HTML GOES HERE ... //
);
};
export default EditRoles;
And below are this result for the code. testing code
My question is, why this api called twice and the pagination sometimes breaking like the video?
Please help what is wrong with the code.
Thank you
Related
I have three apis in all. GetAssets is the first, followed by assetsOptionsList and getAssetsLibrary. The issue I'm having is that when I post the data on getAssetsLibrary, I want to be able to present it on get Assets at runtime.Everything is working fine but i want to show assets on runtime.
I'm setting the runTime state true on get request but the problem is it works only for one time.Second time, it does not map on runtime. Actually, i want to know is there any alternative so that i can achieve the goal.
In the below code the one function is getting the assets. And i want to run the one function when the post request successfully sent.
const [images, setImages] = useState([]);
const [assetOptions, setAssetOptions] = useState([]);
const [faqOpened, setToggleFaq] = useState(false);
const [runTime, setRunTime] = useState(false)
const [assetID, setAssetID] = useState()
const [isLoading, setIsLoading] = useState(false);
const handleForm = (e) => {
const index = e.target.selectedIndex;
const el = e.target.childNodes[index]
const option = el.getAttribute('id');
setAssetID(option)
}
const formHandler = (e) => {
e.preventDefault()
let formData = new FormData();
formData.append('media', e.target.media.files[0]);
formData.append('assetListId', assetID)
formData.append('name', e.target.name.value);
console.log(Object.fromEntries(formData))
const res = axios.post('api/asset-library',
formData
).then((response) => {
showSuccessToaster(response?.data?.message)
setRunTime(true)
setToggleFaq(false)
})
.catch((error) => {
showErrorToaster(error?.response?.data?.message)
})
}
const showSuccessToaster = (response) => {
return uploadToasterSuccess.show({ message: response });
}
const showErrorToaster = (error) => {
return uploadToasterError.show({ message: error });
}
const one = async () => {
setIsLoading(true)
const data = await axios.get('api/assets').then((res) => {
return res?.data?.data
})
setImages(data)
setIsLoading(false)
}
const two = async () => {
const data = await axios.get('/api/asset-list').then((res) => {
return res?.data?.data
})
setAssetOptions(data)
}
useEffect(() => {
one()
two()
}, [runTime]);
I'm storing data using API, it saves successfully, but it's not reloading in the datagrid. I have manually refresh the entire page to view the data. I tried to put the storing variable in a function, then call that function, but it's not rendering I guess. kindly help me. Thank you in advance
here's the code
const ContactDataGrid = ({ rows, columns }) => {
const [platform, setPlatform] = useState([]);
const [searchText, setSearchText] = useState('');
const [Rows, setRows] = useState([]);
const [open, setOpen] = useState(false);
const [formInputData, setformInputData] = useState(
{
name: '',
details: '',
}
);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
const handleChange = (evnt) => {
setOpen(true)
const newInput = (data) => ({
...data,
[evnt.target.name]: evnt.target.value
});
setformInputData(newInput);
}
const showData = () => setRows(rows);
useEffect(() => {
setPlatform(rows);
showData();
}, [rows]);
console.log()
const handleSubmit = (evnt) => {
evnt.preventDefault();
const formData = new FormData(); //formdata object
formData.append('nickname', formInputData.nickname); //append the values with key, value pair
formData.append('target', formInputData.target);
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
axios.post('http://localhost:8006/api/v2/save/beneficiary', formData, config)
.then(response => {
if (response.data.success === true) {
showData()
alert(response.data.message)
}
})
.catch(error => {
alert(error.message);
});
setformInputData({ nickname: "", target: "" });
setOpen(false);
}
function escapeRegExp(value) {
return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
const requestSearch = (searchValue) => {
const searchRegex = new RegExp(escapeRegExp(searchValue), 'i');
const filteredRows = platform.filter((row) => {
return Object.keys(row).some((field) => {
return searchRegex.test(row[field]?.toString() || '');
});
});
setRows(filteredRows);
};
I think when you request success the variable rows don't change so show data load the old data. You can trigger when post data you request fetch data again and change datagrid.
Please I need assistance with a code.
I have a Nextjs dynamic page as my 'stripe_success_url'
Initially I had one product 'courses' whose {id} is beign fetched in the router.query
however, i have created a new product 'ebook' whose {id} is also being fetched in the router.query
I edited the code to differentiate course ID and ebook ID but it is not working yet.
const StripeSuccess = () => {
// state
const [course, setCourse] = useState([]);
const [ebook, setEbook] = useState([]);
const router = useRouter();
const { id } = router.query;
useEffect(() => {
const fetchCourses = async () => {
const { data } = await axios.get('/api/courses');
setCourse(data);
//console.log(data);
};
fetchCourses();
}, [id]);
useEffect(() => {
const fetchEbooks = async () => {
const { data } = await axios.get('/api/ebooks');
setEbook(data);
//console.log(data);
};
fetchEbooks();
}, [id]);
useEffect(() => {
if (id === `${course._id}`) {
const successRequest = async () => {
const { data } = await axios.get(`/api/stripe-success/${id}`);
//console.log(data);
//console.log('SUCCESS REQ DATA', data);
router.push(`/user/course/${data.course.slug}`);
};
successRequest();
}
}, [id]);
useEffect(() => {
if (id === `${ebook._id}`) {
const successEbookRequest = async () => {
const { data } = await axios.get(`/api/stripe-ebooksuccess/${id}`);
//console.log(data);
//console.log('SUCCESS REQ DATA', data);
router.push(`/user/course/${data.ebook.slug}`);
};
successEbookRequest();
}
}, [id]);
Im working on a star wars api app. I am getting an array of people objects, 10 characters. Who all are their own object with different values. However homeworld, and species are urls. So I have to fetch them and store that data to the correct place. I figured out a way to get the homeworld values to each character. However when I try to do it with species I receive undefined. Would appreciate any help this has been kind of a pain thanks ahead of time !
const [people, setPeople] = useState([]);
const [homeWorld, setHomeWorld] = useState([]);
const [species, setSpecies] = useState([]);
const [nextPageUrl, setNextPageUrl] = useState("https://swapi.dev/api/people/");
const [backPageUrl, setBackPageUrl] = useState('');
const [test, setTest] = useState([]);
const fetchPeople = async () => {
const { data } = await axios.get(nextPageUrl);
setNextPageUrl(data.next);
setBackPageUrl(data.previous);
return data.results;
}
const backPage = async () => {
const { data } = await axios.get(backPageUrl);
setCharacters(data.results);
setNextPageUrl(data.next);
setBackPageUrl(data.previous);
}
// Get People
async function getPeople() {
const persons = await fetchPeople();
const homeWorldUrl= await Promise.all(
persons.map((thing) => axios.get(thing.homeworld)),
);
const newPersons = persons.map((person) => {
return {
...person,
homeworld: homeWorldUrl.find((url) => url.config.url === person.homeworld)
};
});
const newPersons2 = newPersons.map((person) => {
return {
...person,
homeWorld: person.homeworld.data.name
};
});
setPeople(newPersons2);
}
// Get Species
async function getSpecies() {
const persons = await fetchPeople();
const speciesUrl = await Promise.all(
persons.map((thing) => axios.get(thing.species)),
);
const newSwapi = persons.map((person) => {
return {
...person,
species: speciesUrl.find((info) => info.data.url === person.species)
};
});
setTest(newSwapi);
// const newPersons2 = newPersons.map((person) => {
// return {
// ...person,
// homeWorld: person.homeworld.data.name
// };
// });
}
useEffect(() => {
getPeople();
getSpecies();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); ```
Species property of person is a array, so your getSpecies() should be like
async function getSpecies() {
const persons = await fetchPeople();
const speciesUrl = await Promise.all(
persons
.filter((thing) => thing.species.length)
.map((thing) => axios.get(thing.species[0]))
);
const newSwapi = persons.map((person) => {
return {
...person,
species: speciesUrl.find((info) => info.data.url === person.species[0])
};
});
setTest(newSwapi);
}
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,
});
};