1

I am having trouble with the setState of objects. My interface definition is as follows;

export interface IProjectData {
  Id?: string,
  Description?: string,
  ProjectState?: string,
}

I access the parameter I sent with RootStackParamList as follows.

function ProjectScreen({ route, navigation }: ProjectProps) {
  const [project, setProject] = useState<IProjeData>(null)

  useEffect(() => {
    const sProject = JSON.stringify(route.params.project)
    let myProject: IProjeData = JSON.parse(sProject)
    console.log('myProject: ')
    console.log(myProject)
    setProject(myProject)
    console.log('Project: ')
    console.log(project)
  }, [])

  return (
    ...
    ...
  )}

Consol output is as follows. Where am I going wrong? Why can't I assign a value to project?

myProject: 
{Id: "bd7acbea", Description"My Test Project", ProjectState"25/25"}
Project: 
null

1 Answer 1

1

setProject is the asynchronous method, and you can't get the updated project value right immediately after setProject.

You should use useEffect with adding a project dependency to get an updated project value.

useEffect(() => {
  console.log(project)
}, [ project ])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.