1

development environment: I am using ReactJS, React Query, Recoil and TypeScript.
I ran into one problem when communicating with REST api. When I get a list through GET communication, I use a query string, but I'm not sure how to dynamically create the query string.
For example 'read?page=1&perPage=10&sorting=created' or 'read?page=1&perPage=20&text=candy&sorting=older' or It could also be 'read?text=snack&category=price'.
Parameter values ​​are managed by Recoil, so I am making a query string by collecting only non-null values, but I am looking for a better way.

Thank you so much for sharing your knowledge!

2 Answers 2

2

Take a look at Template literals.

const pageNum = 3; // you can dynamically set these variables
const perPageNum = 10;
const queryString = `read?page=${pageNum}&perPage=${perPageNum}`;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. But I didn't want template literals. When creating a query string, I want to create something that can put a value if it exists and not put a key and value if it doesn't. For example, if the key text and category has a value, 'read?text=snack&category=food' Or, if only category has a value, you want to know how to make it like 'read?category=book'.
1

A declarative approach based on your comment,

const parameters = {
  pageNum: 3,
  perPageNum: 10,
  category: 'food',
  sorting: null,
};

const queryString = Object.entries(parameters)
  .filter(([_, value]) => value !== null) // [ [ 'pageNum', 3 ], [ 'perPageNum', 10 ], [ 'category', 'food' ] ]
  .map(([key, value]) => `${key}=${value}`) // [ 'pageNum=3', 'perPageNum=10', 'category=food' ]
  .join('&'); // 'pageNum=3&perPageNum=10&category=food'

If you can make an object only with non-nullable value, then you won't need a filter method chaining.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.