invalidateQueries doesn't refetch/refresh the page - javascript

I have a button that, on click, has to perform a thing that makes a list displayed on my page to change, and in theory the page should reload. However, that never happens, no matter how many times I click my button.
Full code of my button:
import React from 'react';
import { useSaveOrderItemsForList } from '../../hooks/Lists/useSaveOrderItemsForList';
import ErrorIndicator from '../shared/ErrorIndicator';
import LoadingButton from '../shared/LoadingButton';
import { valueState as valueStateAtom } from '../../atoms/orderItemsAtom';
import { useSetRecoilState } from 'recoil';
export default function SaveOrderItemsButton({ orderItems, listID }) {
const { isError, error, isLoading, mutate } = useSaveOrderItemsForList(orderItems, listID);
const setValue = useSetRecoilState(valueStateAtom);
const handleClick = () => {
mutate(orderItems, listID);
setValue([]);
}
return (
<div className={'w-100'}>
<br />
<ErrorIndicator isError={isError} error={error} />
<LoadingButton
className={'w-100'}
variant={'success'}
loading={isLoading}
onClick={handleClick}
>
Save
</LoadingButton>
</div>
);
}
As for the code of my custom hook:
import { getToken } from '../../tokens/getToken';
import { basePath } from '../../config/basePath';
import { getTokenAuthHeaders } from '../../functions/sharedHeaders';
import { useMutation, useQueryClient } from 'react-query';
async function saveOrderItemsForList(orderItems, listID) {
const token = await getToken();
const response = await fetch(`${basePath}/lists/save_order_items/${listID}`, {
method: 'PUT',
body: JSON.stringify({ orderItems }),
headers: getTokenAuthHeaders(token)
});
return response.json();
}
export function useSaveOrderItemsForList() {
const queryClient = useQueryClient();
return useMutation(saveOrderItemsForList,
{
onSuccess: () => {
return queryClient.invalidateQueries('lists');
}
}
);
}
My theory is that, since I'm managing the organizing of my list client-side, the page doesn't get updated with the information I passed (this is the code of the page that shows the list):
import Col from 'react-bootstrap/Col';
import CardsList from './CardsList';
import { useList } from '../../hooks/Cards/useList';
import useOrderItemsForCardsInList from '../../hooks/Lists/useOrderItemsForCardsInList';
import usePaginateCardsInList from '../../hooks/Cards/usePaginateCardsInList';
import LoadingAndErrorCentered from '../shared/LoadingAndErrorCentered';
export default function List({ listID }) {
const { isLoading, isError, error, data } = useList(listID);
const { data: orderItems } = useOrderItemsForCardsInList(listID);
const pagesArray = usePaginateCardsInList(orderItems, data);
return (
<Col xs={12}>
<br />
<LoadingAndErrorCentered isLoading={isLoading} isError={isError} error={error} />
{data && <CardsList cards={pagesArray} listID={listID} />}
</Col>
);
}
What do you guys think?
Edit: This is the code of my useList hook.
import { useQuery } from 'react-query';
import { getTokenAuthHeaders } from '../../functions/sharedHeaders';
import { basePath } from '../../config/basePath';
import { getToken } from '../../tokens/getToken';
async function getList(listID) {
const token = await getToken();
const response = await fetch(`${basePath}/cards/list/${listID}`, {
method: 'GET',
headers: getTokenAuthHeaders(token)
});
return response.json();
}
export function useList(listID) {
return useQuery(['cards', 'list', listID], () => {
return getList(listID);
});
}
and on my server, I have this function declared on my endpoint:
static async getList(id) {
const query = await List.findById(id).exec();
return query;
}

queryClient.invalidateQueries('lists');
vs
useQuery(['cards', 'list', listID], () => {});
You are not invalidating the right query keys, so naturally the query doesn't refetch. You need to use the correct key for invalidation, in your case:
queryClient.invalidateQueries(['cards', 'list']);

Related

Getting component to re-render after form submit. Using useContext and custom hooks to fetch data

I'm having some issues getting a component to re-render after submitting a form. I created separate files to store these custom hooks to make them as reusable as possible. Everything is functioning correctly, except I haven't figured out a way to re render a list component after posting a new submit to that list. I am using axios for fetch requests and react-final-form for my actual form. Am I not able to re-render the component because I am using useContext to "share" my data across child components? My comments are set up as nested attributes to each post, which is being handled through Rails. My comment list is rendered in it's own component, where I call on the usePost() function in the PostContext.js file. I can provide more info/context if needed.
**
Also, on a slightly different note. I am having difficulty clearing the form inputs after a successful submit. I'm using react-final-form and most the suggestions I've seen online are for class components. Is there a solution for functional components?
react/contexts/PostContext.js
import React, { useContext, useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { useAsync } from "../hooks/useAsync";
import { getPost } from "../services/post";
const Context = React.createContext();
export const usePost = () => {
return useContext(Context);
};
export const PostProvider = ({ children }) => {
const id = useParams();
const { loading, error, value: post } = useAsync(() => getPost(id.id), [
id.id,
]);
const [comments, setComments] = useState([]);
useEffect(() => {
if (post?.comments == null) return;
setComments(post.comments);
}, [post?.comments]);
return (
<Context.Provider
value={{
post: { id, ...post },
comments: comments,
}}
>
{loading ? <h1>Loading</h1> : error ? <h1>{error}</h1> : children}
</Context.Provider>
);
};
react/services/comment.js
import { makeRequest } from "./makeRequest";
export const createComment = ({ message, postId }) => {
message["post_id"] = postId;
return makeRequest("/comments", {
method: "POST",
data: message,
}).then((res) => {
if (res.error) return alert(res.error);
});
};
react/services/makeRequest.js
import axios from "axios";
const api = axios.create({
baseURL: "/api/v1",
withCredentials: true,
});
export const makeRequest = (url, options) => {
return api(url, options)
.then((res) => res.data)
.catch((err) => Promise.reject(err?.response?.data?.message ?? "Error"));
};
react/components/Comment/CommentForm.js
import React from "react";
import { Form, Field } from "react-final-form";
import { usePost } from "../../contexts/PostContext";
import { createComment } from "../../services/comment";
import { useAsyncFn } from "../../hooks/useAsync";
const CommentForm = () => {
const { post, createLocalComment } = usePost();
const { loading, error, execute: createCommentFn } = useAsyncFn(
createComment
);
const onCommentCreate = (message) => {
return createCommentFn({ message, postId: post.id });
};
const handleSubmit = (values) => {
onCommentCreate(values);
};
return (
<Form onSubmit={handleSubmit}>
{({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<div className="comment-form-row">
<Field name="body">
{({ input }) => (
<textarea
className="comment-input"
placeholder="Your comment..."
type="text"
{...input}
/>
)}
</Field>
<button className="comment-submit-btn" type="submit">
Submit
</button>
</div>
</form>
)}
</Form>
);
};
export default CommentForm;

Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. - useEffect()

I get this error when I try and call a function I have imported within my useEffect() hook in Dashboard.jsx. I am just trying to pull in data from database on the page load pretty much so that when user click button they can send off correct credentials to the api.
I am pulling it in from database for security reasons, so client id is not baked into the code.
I am pretty sure that I am getting this error maybe because the function is not inside a react component? although I am not 100% sure. And if that is the case I am not sure of the best way to restructure my code and get the desired output.
Code below.
mavenlinkCredentials.js
import { doc, getDoc } from "firebase/firestore";
import { useContext } from "react";
import { AppContext } from "../../context/context";
import { db } from "../../firebase";
const GetMavenlinkClientId = async () => {
const {setMavenlinkClientId} = useContext(AppContext)
const mavenlinkRef = doc(db, 'mavenlink', 'application_id');
const mavenlinkDocSnap = await getDoc(mavenlinkRef)
if(mavenlinkDocSnap.exists()){
console.log("mavenlink id: ", mavenlinkDocSnap.data());
console.log(mavenlinkDocSnap.data()['mavenlinkAccessToken'])
setMavenlinkClientId(mavenlinkDocSnap.data()['application_id'])
} else {
console.log("No doc");
}
}
export default GetMavenlinkClientId;
Dashboard.jsx
import React, { useContext, useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useNavigate } from "react-router-dom";
import { query, collection, getDocs, where, setDoc, doc, getDoc } from "firebase/firestore";
import { auth, db, logout } from "../firebase";
import { Button, Container, Grid, Paper } from "#mui/material";
import ListDividers from "../components/ListDividers";
import { AppContext } from "../context/context";
import axios from "axios";
import {SuccessSnackbar, ErrorSnackbar} from '../components/PopupSnackbar';
import GetMavenlinkClientId from "../helpers/firebase/mavenlinkCredentials";
const Dashboard = () => {
const [user, loading, error] = useAuthState(auth);
const [name, setName] = useState("");
const [ accessToken, setAccessToken ] = useState("")
const [errorAlert, setErrorAlert] = useState(false);
const [successAlert, setSuccessAlert] = useState(false);
const [mavenlinkClientId, setMavenlinkClientId] = useState("");
const {isAuthenticated} = useContext(AppContext);
const navigate = useNavigate();
const uid = user.uid
const parsedUrl = new URL(window.location.href)
const userTokenCode = parsedUrl.searchParams.get("code");
const { mavenlinkConnected, setMavenlinkConnected } = useContext(AppContext)
const { maconomyConnected, setMaconomyConnected } = useContext(AppContext)
const { bambooConnected, setBambooConnected } = useContext(AppContext)
const fetchUserName = async () => {
try {
const q = query(collection(db, "users"), where("uid", "==", user?.uid));
const doc = await getDocs(q);
const data = doc.docs[0].data();
setName(data.name);
} catch (err) {
console.error(err);
alert("An error occured while fetching user data");
}
};
//
useEffect(() => {
if (loading) return;
if (!user) return navigate("/");
fetchUserName();
if(userTokenCode !== null){
authorizeMavenlink();
}
if(isAuthenticated){
GetMavenlinkClientId()
}
}, [user, loading]);
///put this into a page load (use effect maybe) so user does not need to press button to connect to apis
const authorizeMavenlink = () => {
console.log(uid);
const userRef = doc(db, 'users', uid);
axios({
//swap out localhost and store in variable like apitool
method: 'post',
url: 'http://localhost:5000/oauth/mavenlink?code='+userTokenCode,
data: {}
})
.then((response) => {
setAccessToken(response.data);
setDoc(userRef, { mavenlinkAccessToken: response.data}, { merge: true });
setMavenlinkConnected(true);
setSuccessAlert(true);
})
.catch((error) => {
console.log(error);
setErrorAlert(true)
});
}
//abstract out client id and pull in from db
const getMavenlinkAuthorization = () => {
window.open('https://app.mavenlink.com/oauth/authorize?client_id='+mavenlinkClientId+'&response_type=code&redirect_uri=http://localhost:3000');
window.close();
}
const authorizeBamboo = () => {
axios({
method: 'get',
url: 'http://localhost:5000/oauth/bamboo',
data: {}
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error);
});
// console.log('bamboo connected')
setBambooConnected(true);
}
const authorizeMaconomy = () => {
console.log("Maconomy connected")
setMaconomyConnected(true);
}
const syncAccount = async() => {
if(!mavenlinkConnected){
await getMavenlinkAuthorization()
}
if (!bambooConnected){
await authorizeBamboo();
}
if (!maconomyConnected){
await authorizeMaconomy();
}
}
const handleAlertClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setSuccessAlert(false) && setErrorAlert(false);
};
console.log(mavenlinkClientId);
return(
<>
<Container>
<div className="dashboard">
<h1>Dashboard</h1>
<Grid container spacing={2}>
<Grid item xs={12}>
<Paper style={{paddingLeft: "120px", paddingRight: "120px"}} elevation={1}>
<div className="dashboard-welcome">
<h2>Welcome {name}</h2>
<h4>{user?.email}</h4>
<hr/>
<h2>Integrations</h2>
<Button onClick={syncAccount}>
Sync Account
</Button>
{/* <Button onClick={getMavenlinkClientId}>
Bamboo Test
</Button> */}
<ListDividers/>
</div>
</Paper>
</Grid>
</Grid>
</div>
{successAlert === true ? <SuccessSnackbar open={successAlert} handleClose={handleAlertClose}/> : <></> }
{errorAlert === true ? <ErrorSnackbar open={errorAlert} handleClose={handleAlertClose}/> : <></> }
</Container>
</>
);
}
export default Dashboard;
the error is because you’re calling const {setMavenlinkClientId} = useContext(AppContext) inside the file mavenlinkCredentials.js which is not a react components.
you could maybe change the function inside mavenlinkCredentials.js to accept a setMavenlinkClientId and pass it from outside like this.
const GetMavenlinkClientId = async (setMavenlinkClientId) => {
const mavenlinkRef = doc(db, 'mavenlink', 'application_id');
const mavenlinkDocSnap = await getDoc(mavenlinkRef)
if(mavenlinkDocSnap.exists()){
console.log("mavenlink id: ", mavenlinkDocSnap.data());
console.log(mavenlinkDocSnap.data()['mavenlinkAccessToken'])
setMavenlinkClientId(mavenlinkDocSnap.data()['application_id'])
} else {
console.log("No doc");
}
}
and then you can call this function in your dashboard.js like so,
const {setMavenlinkClientId} = useContext(AppContext)
if(isAuthenticated){
GetMavenlinkClientId(setMavenlinkClientId)
}

Problem when maping array - React with Redux Toolkit

I have the following problem: I use a fatch API to get all the products I have registered in my database (mongodb), then I store the result in a slice called products-slice which has an array as its initial state empty. Until then everything is in order. As I need information the time the homepage is loaded, I use the useEffect hook to fetch the products I have registered. Then I pass this array as props to a component, and make a map. The problem is that when the component loads, the information is not local.
código do backend
module.exports.fetchProduct = async (req, res) => {
try {
const products = await Product.find({});
if (products) {
res.json(products);
}
} catch (error) {
console.log(error);
}
};
productsActions.js
export const fetchProducts = () => {
return async (dispatch) => {
try {
const response = await fetch("http://localhost:xxxx/xxxxxx");
const data = await response.json();
let loadedProducts = [];
for (const key in data) {
loadedProducts.push({
id: data[key]._id,
productName: data[key].productName,
price: data[key].price,
imageUrl: data[key].imageUrl,
});
}
dispatch(setProducts(loadedProducts));
} catch (error) {
console.log(error);
}
};
};
home.jsx
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Container } from "react-bootstrap";
import {fetchProducts} from '../../store/actions/productsActions';
import Hero from "../hero/Hero";
import Footer from "../footer/Footer";
import DisplayProductsList from "../displayProduct/DisplayProductsList";
export default function Home() {
const productsInfo = useSelector((state) => state.products.products);
console.log(productsInfo);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchProducts());
}, [dispatch]);
return (
<>
<Hero />
<DisplayProductsList products={productsInfo} />
<Container fluid>
<Footer></Footer>
</Container>
</>
);
}
product-slice.js
const initialState = {
products: [],
};
const productSlice = createSlice({
name: "product",
initialState,
reducers: {
setProducts(state, action) {
state.products.push(action.payload);
},
},
});
export const { setProducts } = productSlice.actions;
export default productSlice.reducer;
component where I'm mapping
export default function DisplayProductsList(props) {
console.log(props);
return (
props.products.map((product) => (
<DisplayProducts
key={product.id}
imageUrl={product.imageUrl}
name={product.productName}
price={product.price}
/>
))
);
}
console.log output in the above component
enter image description here

TypeError: Cannot read property '_id' of undefined ReactJs?

I am trying to get the name of a user based on the user id, using a .map() method. The code that I wrote seems good to me, however, I get the error mentioned in the question title and the page won't render.
See the image below:
Here's an image of the error stack:
And here's the code I have:
import { SearchBox } from "../SearchBox"
import { StyledNavBar, NavSection, StyledLink, StyledLogo } from "./styles"
import logo from './Logo2.png'
import { useDispatch } from "react-redux"
import { useHistory } from "react-router"
import axios from "axios"
import { useEffect, useState } from "react"
function useApi() {
const userId = localStorage.getItem('userId')
const dispatch = useDispatch()
const [UserNames, setUserNames] = useState()
useEffect(() => {
async function getData() {
try {
const { data } = await axios({
method: 'GET',
baseURL: process.env.REACT_APP_SERVER_URL,
url: '/users'
})
console.log(data)
dispatch(setUserNames(data))
}catch(error){
dispatch(console.log(error))
}
}
getData()
}, [])
return { userId, UserNames }
}
export const NavBar = function({}) {
const { userId, UserNames } = useApi()
console.log(UserNames)
const token = localStorage.getItem('token')
const dispatch = useDispatch()
const history = useHistory()
function handleClick(){
dispatch({type: 'USER_LOGOUT'})
localStorage.clear()
history.push('/')
}
return(
<StyledNavBar>
<NavSection>
{!token && <StyledLink to='/login'>Ingresar</StyledLink>}
{!token && <StyledLink to='/signup'>Registrarse</StyledLink>}
<StyledLink to='/'>Categorías</StyledLink>
<StyledLink to='/'><StyledLogo src={logo} /></StyledLink>
{token && <StyledLink to='/'>Mis Transacciones</StyledLink>}
{token && <StyledLink to='/sellproduct'>Vender</StyledLink>}
{!!UserNames && UserNames.length > 0 && UserNames.map((usr, i) => {
return usr[i]._id === userId ?
<p>{usr[i].name}</p>
:
''
})}
<SearchBox />
{token && <button type='button' onClick={handleClick}>Cerrar Sesión</button>}
</NavSection>
</StyledNavBar>
)
}
So it's pretty much telling me that the usr[i]._id line is not correct, but as far as I can see nothing is wrong with that code.
I think you might just want usr and not usr[i]? The map() gives you the individual item from the iterable.

getting mongodb data from express server using fetch on reactjs frontend

Creating a notes app on MERN stack https://lutif.github.io/Notes-Keeper/ ,
I have a mongodb , I want to fetch notes on database and then render those on frontend. However reactjs doesn't allow me to initialize state (call useState) in a call back. how do it get my fetch data and use it in useState. any pointer will be helpful.
import React, { useState } from "react";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";
import addNotedb from '../APICalls/addNote';
import getNotesListdb from '../APICalls/getNotesList';
function App() {
getNotesListdb().then(nojson=>nojson.json()).then( notesListdb=>
{const [notes, setNotes] = useState([...notesListdb]);}
)
function addNote(newNote) {
// const noteId =
addNotedb(newNote);
console.log('calling add note with ', newNote);
// newNote.Id = newNote;
setNotes(prevNotes => {
return [...prevNotes, newNote];
});
}
function deleteNote(id) {
setNotes(prevNotes => {
return prevNotes.filter((noteItem, index) => {
return index !== id;
});
});
}
return (
<div>
<Header />
<CreateArea onAdd={addNote} />
{notes.map((noteItem, index) => {
return (
<Note
key={index}
id={index}
title={noteItem.title}
content={noteItem.content}
onDelete={deleteNote}
/>
);
})}
<Footer />
</div>
);
}
export default App;
const endpoint = '/api/notes';
export default function getNotes() {
let promise =
fetch(endpoint, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
}
)
return promise
}

Categories

Resources