Home > Software engineering >  React Native: pass variable to another page
React Native: pass variable to another page

Time:04-01

I have implemented a way that when I click on a button I pass a variable (an object that I build when the button is clicked) to another page.

Now my problem is in the page that receives this variable, because when I pass this value, I use it to set other const variable and if I'll click another time in the button the variables remains setted as before.

So I have an index.js page that contains the botton

const index = ({}) => {
return (
// others //
 <Permission /> 
)
}

In the Permission.js

const Permission = () => {

 const request = () => {
   let requestVariable 
   // all the logic to populate the requestVariable
   if(//.....){
     requestVariable = {
            id: idRequest,
            requestType: 'permission',
            startDate: myDateVariable
            // ....
   }
   Actions['allPermissions']{(requestVariable : requestVariable  )}
 }

 return (
       <MyButton  type="primary" onPress={() => request()} />
 )
}

So I have my AllPermissions.js

const AllPermission = ({requestVariable}){ const[componentSel, setComponentSel] = useState(0)

return( {componentSel === 0 && <NewPermission requestVariable = {requestVariable } />} ) }

Now in NewPermission I have the problems I talked about

const NewPermission = ({requestVariable }){
    const [type, setType] = useState(requestVariable  ? requestVariable.requestType : 'permission'
    const [startDate, setStartDate] = useState(requestVariable ? requestVariable.startDate : new Date())
//....
}

Now as I said the problem is in new request, because I can access in this page clicking in the button or from a tab. If I click on the button first time, all is setted correctly but If I go to the index.js page and click another time, (so the values that I insert in the object are different) are not showed. How can I do to populate the values in my NewPermission page?

CodePudding user response:

Try this way

const NewPermission = ({requestVariable }){
    const [type, setType] = useState(requestVariable  ? requestVariable.requestType : 'permission'
    const [startDate, setStartDate] = useState(requestVariable ? requestVariable.startDate : new Date())

 useEffect(() => {
    setType( requestVariable ? requestVariable.requestType : 'permission' );
  }, [requestVariable]);
}
  • Related