Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Writing an object of state values #479

Closed
xavierakram opened this issue Jul 15, 2020 · 1 comment
Closed

Writing an object of state values #479

xavierakram opened this issue Jul 15, 2020 · 1 comment
Labels
question Further information is requested

Comments

@xavierakram
Copy link

xavierakram commented Jul 15, 2020

Hi there, just trying to get my head around using Recoil in an application and I've got the following use-case:

const [totals, setTotals] = React.useState<Totals>({ gross: 0, vat: 0, total: 0, savings: 0, });

How would I create this as a Recoil state object? I've tried the following:

export const payment_state = {
  plan: atom({
    key: 'plan',
    default: '',
  }),
  seats: atom({
    key: 'seats',
    default: 2,
  }),
  unitPrice: atom({
    key: 'unitPrice',
    default: 35,
  }),
  product: atom({
    key: 'product',
    default: products[0] as IProductsType,
  }),
  totals: {
    gross: atom({
      key: 'gross',
      default: 0,
    }),
    vat: atom({
      key: 'vat',
      default: 0,
    }),
    total: atom({
      key: 'total',
      default: 0,
    }),
    savings: atom({
      key: 'savings',
      default: 0,
    }),
  },
};

Which is causing typescript errors, because totals isn't an atom.

@drarmstr
Copy link
Contributor

drarmstr commented Jul 15, 2020

It's fine to construct objects that contain atoms or selectors to represent your state. But, what is your error exactly? Are you trying to pass in totals directly to a hook such as useRecoilState()? It is correct that only atoms or selectors should be used for that hook parameter. e.g.

  const [gross, setGross] = useRecoilState(payment_state.totals.gross);

If you'd like to use all of the atoms at once, you could use waitForAll(), though it is currently read-only.

  const {gross, vat, total, savings} = useRecoilValue(waitForAll(payment_state.totals));

It is generally recommended to use atoms to represent primitives or simple values, as atoms and selectors are the granularity of subscriptions. However, if that isn't a concern and it is laborious to do so, you are free to store richer objects in atoms.

@drarmstr drarmstr added the question Further information is requested label Jul 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants