Issue
I want to make hook to get data from Snapshot to display proposals. I use graphql-request library to get data. I want to get this data in component for example: const { data } = useSnapshotProposalsQuery(). How can i do this? For now i can only get const data = useSnapshotProposalsQuery() and when i am console.log(data) i get Promise{<opening>}. My code:
import { gql, request } from 'graphql-request';
export const useSnapshotProposals = gql`
query Proposals {
proposals(
first: 20
skip: 0
where: { space_in: ["example.eth"] }
orderBy: "created"
orderDirection: desc
) {
id
title
body
choices
start
end
snapshot
state
author
space {
id
name
}
}
}
`;
export const useSnapshotProposalsQuery = () => {
return request('https://hub.snapshot.org/graphql', useSnapshotProposals).then((data) => data);
};
Solution
You create a custom hook. and that hook returns a state. when sideeffect inside that hook happens, the state is updated and your outer component gets re-rendered. (react docs)
export const useSnapshotProposalsQuery = () => {
const [myData, setMyData] = useState(null);
useEffect(()=>{
request('https://hub.snapshot.org/graphql', useSnapshotProposals).then((data) => {setMyData(data)});
}, []); // run only one time
return myData;
};
in outer component:
function ABCcomponent () {
const myData = useSnapshotProposalsQuery(); // it will be null at first, but will be filled with data later.
return (
/*ui that uses myData */
)
}
Answered By - irous
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.