Hi all,
I am trying to update the state to a value sent by a button click (in this case a url), I am new to react so I’m having trouble working out what is the best practice here, if anyone could help explain I would be most grateful. I’m getting a “url is not defined” error so assuming the way I’m sending the props is not correct?
Thanks in advance,
Leon.
Hey @leonnockolds,
I also had that issue when I started with frontity. Its actually quite simple. All you need to do is this:
actions: {
theme: {
updateMixcloudLink: ({ state }) => (props) => {
//Do your thing with props
}
}
}
GL. Let me know if we can help with something else.
@ni.bonev Thankyou so much for taking the time to help, if you could be so kind to explain a bit further, is the syntax correct that I’m using on the button to send the props?
<Button onClick={actions.theme.updateMixcloudLink} url="this-is-the-url-i-want-to-send-to-the-state">
CHANGE MIXCLOUD URL
</Button>
state: {
theme: {
mixcloudLink: "https://www.mixcloud.com/sohoradio/chris-p-cuts-30082021/",
},
},
actions: {
theme: {
updateMixcloudLink: ({ state }) => (url) => {
state.theme.mixcloudLink = { url };
},
},
},
Hey @leonnockolds,
i think you are confusing your component props with your action(function) arguments.
So, your function called updateMixcloudLink
expect to receive 1, argument, named as url
.
So here is what you need to do:
Slightly update your action:
actions: {
theme: {
updateMixcloudLink: ({ state }) => (url) => {
state.theme.mixcloudLink = url;
},
},
},
Then when you want to use the action, you can do it like this:
const { updateMixcloudLink } = actions.theme
<Button onClick={() => updateMixcloudLink("this-is-the-url-i-want-to-send-to-the-state")}>
CHANGE MIXCLOUD URL
</Button>
1 small note. When your function requires a argument, you have to always pass an arrow function that invokes your function like this:
onClick={() => updateMixcloudLink("this-is-the-url-i-want-to-send-to-the-state")}
If you just do this:
onClick={updateMixcloudLink("this-is-the-url-i-want-to-send-to-the-state")}
then updateMixCloudLink will be invoked as the component is rendered, not when you click it.
I hope that is not adding extra confusion.
Good luck
1 Like
@ni.bonev Nikolay, thank you so much for your help with this! This was the final piece I needed in order to finish up my site. All done and working exactly as I want it to
1 Like