I am using React native and I have a context variable post, it has an attribute called name and I have defined a function called onChange to set it.
import React, { useState } from "react";
const PostContext = React.createContext({
content: "",
onChange: (newPostContent: string) => {},
});
export const PostContextProvider = ({ children }) => {
const [content, setContent] = useState("");
const postChangeHandler = (newPostContent: string) => {
setContent(newPostContent);
};
return (
<PostContext.Provider
value={{ content, onChange: postChangeHandler }}
>
{children}
</PostContext.Provider>
);
};
export default PostContext;
Now I have a page on which I want to fetch a post from Amplify's GraphQL API and set its content to my context variable, so I can use it on other pages.
import React, { useEffect, useContext } from "react";
import { API, graphqlOperations} from "aws-amplify";
import PostContext from "./context/post-context";
const post = useContext(PostContext);
const fetchPost = async () => {
const {data: {getPost: { postContent },},} = await API.graphql(
graphqlOperation(`
query GetPost {
getPost(id: "${some post Id}") {
content
}
}
`)
);
post.onChange(postContent)
}
useEffect(()=>{
fetchPost()
}, [])
useEffect(()=>{
console.log(post.content)
}, [post])
What I expect is that in the async function, the execution is blocked until postContent (because of the await and then it's value is assigned to the context variable, or its update is schedualed (that's why I have also included a useEffect to console.log the value of post.content. But it is not updated and its value remains an empty screen. Can somebody help me with this? I am learning React native how this work, so a detailed answer that lets me know what I am doing wrong is appreciated.