I'm learn from projects Javascript Everywhere book. I have a problem when i'm doing delete (mutation) action. in the Backend, Delete Mutation works normally. But in the front end. let's say i'm have 2 pages that querying notes. Home and MyNotes.
Home page
My Notes Page
When i'm clicking delete note. it direct to '/mynotes' page, and delete the note. UI update normaly when i'm deleting inside mynotes page, but when i'm going to home page, notes that has been delete before is still showing.
here's my code
DeleteNote.js
import React from 'react';
import { useMutation } from '#apollo/client';
import { withRouter } from 'react-router-dom';
import ButtonAsLink from './ButtonAsLink';
import { DELETE_NOTE } from '../gql/mutation';
import { GET_MY_NOTES, GET_NOTES } from '../gql/query';
const DeleteNote = props => {
const [deleteNote] = useMutation(DELETE_NOTE, {
variables: {
id: props.noteId
},
// refetch the note list queries to update the cache
refetchQueries: [{ query: GET_MY_NOTES, GET_NOTES }],
onCompleted: data => {
// redirect the user to the "my notes" page
props.history.push('/mynotes');
},
options: {
fetchPolicy: 'cache-first',
errorPolicy: 'ignore'
}
});
return <ButtonAsLink onClick={deleteNote}>Delete Note</ButtonAsLink>;
};
export default withRouter(DeleteNote)
;
delete mutation
const DELETE_NOTE = gql`
mutation deleteNote($id: ID!) {
deleteNote(id: $id)
}
`;
i want to delete note in homepage with realtime results. i don't have any idea , i'm beginner in graphQL. any help will be appreciated, thank you.
Related
import React, { useState ,useEffect} from 'react';
import { Link ,useHistory,useParams} from 'react-router-dom';
import { getDatabase,ref, child, get } from 'firebase/database';
import { auth, db } from './Config/Config';
export default function User()
const [user,setUser]=useState()
const {id}=useParams();
const dbRef = ref(getDatabase());
get(child(dbRef, AllUsers/${id})).then((snapshot) => {
if (snapshot.exists()) {
setUser(...snapshot.val());
} else {
console.log('user',user)
return (
{id}
</div>
)
}
IDK how to use that firebase id tho but if want to show data getting as responses then you already store firebase data in the local-state now you can use that state to get data and show anywhere {user.id} or whatever ur getting in response!
It's a design pattern using lowercase as params. So rename to allusers or all-users.
Are you sure you getting the right ID from params ?
also, paste your full code pls.
I am working in React, and I have a mutation that will be called essentially the exact same way across a multitude of different files. Rather than type the same syntax over and over, I attempted to make a hook file that would carry out the process, and I could just import it and call it from inside the many components that need this mutation. However, I am hitting the following error...
React Hook "useMutation" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
The error is clear enough, I can see what the issue is, but I have no idea how to create a custom React Hook Function and the site to which the direct me to is not particularly helpful. Would someone be able to explain to me how to make this file a 'react hook?'
import React from "react";
import { useMutation } from "#apollo/client";
import { MANAGER_REFRESH, OWNER_REFRESH } from "../../graphql/operations";
const [managerRefresh, { loading: loadingM, error: errorM, data: dataM}] = useMutation(MANAGER_REFRESH)
const [ownerRefresh, { loading: loadingO, error: errorO, data: dataO}] = useMutation(OWNER_REFRESH)
const refresh = async (role, userId) => {
if (role === "MANAGER"){
return await managerRefresh({
variables: {
role: role,
id: userId
}
})
}
else if (role === "OWNER"){
return await ownerRefresh({
variables: {
role: role,
id: userId
}
})
}
}
export default refresh
Every time when my redux state is updating my whole page is loading. Not exactly loading resources back from server but refreshing the components inside the page?
The following is my store code.
P.S : I am using multiple stores and combining them using combine reducers.
import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import logger from "redux-logger";
import { User } from "./User";
import { Restaraunt } from "./Restaraunt";
import { Dish } from "./Dishes";
import { Cart } from "./Cart";
import { createForms } from "react-redux-form";
import { InitialFeedback, RegisterUserDetails, RegisterRestarauntDetails, addDishDetails } from "./forms";
export const storeConfig = () => {
const store = createStore(
combineReducers({
user: User,
restaraunts: Restaraunt,
dishes: Dish,
cart: Cart,
...createForms({ feedback: InitialFeedback }),
...createForms({ registeruser: RegisterUserDetails }),
...createForms({ registerres: RegisterRestarauntDetails }),
...createForms({ addDish: addDishDetails })
}),
applyMiddleware(thunk, logger)
);
return store;
};
I So I am using the cart that I mentioned a particular page. So when ever my cart is updating then my whole page is loading again.
This a bit too broad to be honest.
You should take a look at every component in your react app and make sure that they only re-render when needed.
Things you can do:
You can use shouldComponentUpdate lifecycle if you have class-based components that should update only when few of the props change.
You can use React.memo to memoize a component and prevent unnecessary rerender.
useCallback hook on functions for memorizing them.
im brand new to Next.js and i have the following situation. i want to redirect the user to the route /messages if he type route /messages/123 based on css media query so if he is mobile we will not redirect and if he in browser then redirect .
i have tried the following code
import React, { useLayoutEffect } from 'react';
import { useRouter, push } from 'next/router';
import useMediaQuery from '#material-ui/core/useMediaQuery';
import Layout from '../components/Customer/Layout/Layout';
import Chat from '../components/Customer/Chat/Chat';
const Messages = () => {
const { pathname, push } = useRouter();
const matches = useMediaQuery('(min-width:1024px)');
useLayoutEffect(() => {
console.log('I am about to render!');
if (matches && pathname === '/messages') {
console.log('match!');
push('/');
}
}, [matches, pathname, push]);
return (
<Layout currentURL={pathname}>
<Chat />
</Layout>
);
};
export default Messages;
the problem is the component render twice before redirect
But You should probably be using useEffect since you are not trying to do any DOM manipulations or calculations.
useLayoutEffect: If you need to mutate the DOM and/or DO need to perform measurements
useEffect: If you don't need to interact with the DOM at all or your DOM changes are unobservable (seriously, most of the time you should use this).
You should see immediate action.
Edit:
You can use Next JS getInitialProps to check the request headers and determine if the request if from mobile or desktop then redirect from there.
getInitialProps({ res, req }) {
if (res) {
// Test req.headers['user-agent'] to see if its mobile or not then redirect accordingly
res.writeHead(302, {
Location: '/message'
})
res.end()
}
return {}
}
Is it possible to access the URL params supplied in a route outside the components?
This of course can be accomplished with window.location but I am looking for something in the react-router API to do this more cleanly.
Additionally, if there is a more standard approach to doing this with GraphQL, that's even better! I am just looking into browser clients for gql and new to gql in general.
Example component:
import React from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import get from 'lodash.get';
const ContractComponent = (props) => {
...
};
const ContractQuery = gql`query ContractQuery ($contractId: String!){
contract(id: $contractId) {
...
}
}`;
const ContractWithData = graphql(ContractQuery, {
options: { variables: { contractId: contractId } }, // <-- var i want to pull from url params
})(ContractComponent);
export default ContractWithData;
Example route:
<Route path="contract/:contractId" component={Contract} />
I'm not really familiar with react-apollo, but I think the following is a good way to achieve what you want.
You can see in the docs that options can be a function taking the component props as input, returning an object with the options: http://dev.apollodata.com/react/queries.html#graphql-options
So I think you can do:
const ContractWithData = graphql(ContractQuery, {
options: props => ({ variables: { contractId: props.params.contractId } })
})(ContractComponent);
In the code above, props.params are the params passed by react-router to the route component (nothing special there).
You want to write options as a function when you need do to something dynamic at runtime, in this case accessing the route params.
Hope it helps.