javascript - How can i update a specific value of a recoil state object - Stack Overflow

I have this recoil state object:export const LivePolygon = atom({key: "LivePolygon",default:

I have this recoil state object:

export const LivePolygon = atom({
    key: "LivePolygon",
    default: {
        radii: ['', ''],
        coordinates: ['', ''],
        tilt: ['']
      },
});

And on another file i import it like this:

import { LivePolygon } from "../TheFileOfLivePolygon";

const [liveP, setLiveP] = useRecoilState(LivePolygon);

Now i want to update a specific value of it (from the other file, where it's being imported to).

For Example, if i want to update the object radii in the second cell to be equal to 5.

With a simple variable i'd do it like this:

liveP.radii[1] = 5

How can i do it here? I saw a few questions about it, but non of them helped with this case.

I have this recoil state object:

export const LivePolygon = atom({
    key: "LivePolygon",
    default: {
        radii: ['', ''],
        coordinates: ['', ''],
        tilt: ['']
      },
});

And on another file i import it like this:

import { LivePolygon } from "../TheFileOfLivePolygon";

const [liveP, setLiveP] = useRecoilState(LivePolygon);

Now i want to update a specific value of it (from the other file, where it's being imported to).

For Example, if i want to update the object radii in the second cell to be equal to 5.

With a simple variable i'd do it like this:

liveP.radii[1] = 5

How can i do it here? I saw a few questions about it, but non of them helped with this case.

Share Improve this question edited May 4, 2022 at 20:21 Mike Hemilton asked May 4, 2022 at 20:02 Mike HemiltonMike Hemilton 1114 silver badges15 bronze badges 2
  • Yes, but obviously you can't do it like that when it's a recoil state... – Mike Hemilton Commented May 4, 2022 at 20:21
  • That's almost right, but it's actually ending up adding a new value and creating a third cell for it: radii[2], not editing the existin value in the radii[1] – Mike Hemilton Commented May 4, 2022 at 20:31
Add a ment  | 

3 Answers 3

Reset to default 3

Here's a mented example of how to update an object value in a Recoil atom. Just make sure not to mutate any objects while updating it (the same is true for any React state).

body { font-family: sans-serif; }
button, pre { font-size: 1rem; }
pre { font-family: monospace; }
<div id="root"></div><script src="https://unpkg./[email protected]/umd/react.development.js"></script><script src="https://unpkg./[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg./[email protected]/umd/recoil.min.js"></script><script src="https://unpkg./@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

// import * as ReactDOM from 'react-dom/client';
// import {atom, RecoilRoot, useRecoilState} from 'recoil';

// This Stack Overflow snippet demo uses UMD modules instead of the above import statments
const {atom, RecoilRoot, useRecoilState} = Recoil;

// It won't make any difference whether you define this atom
// here in this module or define it in another module and import it:
const livePolyAtom = atom({
  key: 'livePolygon',
  default: {
    radii: [0, 0],
    coordinates: [0, 0],
    tilt: [0],
  },
});

function App () {
  const [livePoly, setLivePoly] = useRecoilState(livePolyAtom);

  const updateRadiiValue = () => {
    // Make sure not to mutate any objects when returning the new object state:
    setLivePoly(lp => {
      const radii = [...lp.radii];
      radii[1] = 5;
      return {...lp, radii};
    });
  };

  return (
    <div>
      <button onClick={updateRadiiValue}>Update radii value</button>
      <pre><code>{JSON.stringify(livePoly, null, 2)}</code></pre>
    </div>
  );
}

const reactRoot = ReactDOM.createRoot(document.getElementById('root'));

reactRoot.render(
  <RecoilRoot>
    <App />
  </RecoilRoot>
);

</script>

Let's say I have a userState

import {atom} from 'recoil';

export const userState = atom({
  key: 'userState',
  default: {
    userId: 1,
    firstName: 'John',
    lastName: 'Doe',
  },
});

If I want to change only the firstName of the user

import {useRecoilState} from 'recoil';
import {userState} from '../../store/User';

const Home = () => {
  const [user, setUser] = useRecoilState(userState);

  const changeFirstName = () => {
    setUser({...user, firstName: 'Jane'});
  };

  return (
    <>
      <h1>{`${user.firstName} ${user.lastName}`}</h1>
      <Button onClick={changeFirstName}>
        Change First Name
      </Button>
    </>
  );
};

Updated objects can be generated inline using + the setter arg immer

import {produce} from "immer"

<DatePicker
    label="Date"
    value={form.start_date}
    onChange={newDate =>
       setDetails(oldForm => produce(oldForm, () => {
       oldForm.start_date = newDate
    }))
   }
/>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745439147a4627750.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信