Ryan Fonseka
Ryan Fonseka

Reputation: 255

Error in setting a value to useState variable in function

I have a button that calls a function when it is pressed. I want to set startJob = false. when I added the following code it gives me an error

TypeError: setJobStart is not a function. (In 'setJobStart(false)', 'setJobStart' is undefined)

My code:

function App(){
    const [arrived, setArrived ] = useState(false);
    const [startJob, setJobStart ] = useState(false);
 return(
    <ActionButtons />
 )
}

function ActionButtons ({arrived, startJob, dialer, directions}) {
    return(
    <Button title="Arrived" disabled={arrived} onPress={() => ArrivedOk()} buttonStyle={{ backgroundColor: '#0b77b0' }}></Button>
)})

My function :

function ArrivedOk (setJobStart,startJob){
 console.log("OK");
 setJobStart(false);
 // setArrived(true);
}

Upvotes: 0

Views: 52

Answers (1)

Sanket Shah
Sanket Shah

Reputation: 3091

You don't have to pass setJobStart as an argument to ArrivedOk function because it's already defined in :

const [startJob, setJobStart ] = useState(false);

Pass arrived, startJob, setJobStart, dialer, directions as a prop to ActionButtons component:

function App(){
    const [arrived, setArrived ] = useState(false);
    const [startJob, setJobStart ] = useState(false);
 return(
    <ActionButtons arrived={arrived} startJob={startJob} setJobStart={setJobStart}/> // <--- same for dialer and directions
 )
}

NOTE: Don't pass dialer, directions extra props if you're not going to use them inside your component


Modify your ActionButtons component like this:

function ActionButtons ({arrived, startJob, setJobStart, dialer, directions}) {
    return(
    <Button title="Arrived" disabled={arrived} onPress={() => ArrivedOk()} buttonStyle={{ backgroundColor: '#0b77b0' }}></Button>
)})

Modify your ArrivedOk function as below:

And there is no need to pass startJob as well because you can get startJob's value directly from the state.

function ArrivedOk (startJob){
 console.log("OK");
 setJobStart(false); 
 // setArrived(true);
}

Upvotes: 3

Related Questions