reactjstypescriptreduxreact-reduxmiragejs

how the data is destructured in this example?


im making a project diary App by follwing an article. it uses redux toolkit and miraj as a fake server. it has a component named Editor

 const Editor: FC = () => {
  const { currentlyEditing: entry, canEdit, activeDiaryId } = useSelector(
    (state: RootState) => state.editor
  );
  const [editedEntry, updateEditedEntry] = useState(entry);
  const dispatch = useAppDispatch();

  const saveEntry = async () => {
    if (activeDiaryId == null) {
      return showAlert('Please select a diary.', 'warning');
    }
    if (entry == null) {
      http
        .post<Entry, { diary: Diary; entry: Entry }>(
          `/diaries/entry/${activeDiaryId}`,
          editedEntry
        )
        .then((data) => {
          if (data != null) {
            const { diary, entry: _entry } = data;
            dispatch(setCurrentlyEditing(_entry));
            dispatch(updateDiary(diary));
          }
        });

as a newbie im unable to understand following:

enter code here const { currentlyEditing: entry, canEdit, activeDiaryId } = useSelector(

in this line to my understanding entry is a type. but there is no type or interface of entry in article. 2ndly

 .post<Entry, { diary: Diary; entry: Entry }>(
          `/diaries/entry/${activeDiaryId}`,

we are making a post request and in miraj server we have defined routes as:

this.post('/diaries/entry/:id', diary.addEntry);

i dont understand this :id part. how we would get the id over here?

and last thing :) in this line: const { diary, entry: _entry } = data; dispatch(setCurrentlyEditing(_entry)); why there is underscore before entry? and same question like above that is it a type for typescript or some destructuring method that i dont know.


Solution

  • code here const { currentlyEditing: entry, canEdit, activeDiaryId } = useSelector(
    

    in this line to my understanding entry is a type. but there is no type or interface of entry in article. 2ndly

    No, this is not a type. This is JS lingo for renaming destructured properties. The code is simply taking currentlyEditing and renaming it to entry. This is also the case for const { diary, entry: _entry } = data, hence dispatch(setCurrentlyEditing(_entry)).

    this.post('/diaries/entry/:id', diary.addEntry);
    

    i dont understand this :id part. how we would get the id over here?

    This is basically a placeholder for retrieving dynamic parameters that you collect from your URL, for example if the URL is http://www.website.org/diaries/entry/123, then id=123, which mirage will automatically parse out from the route. Please refer to the doc section here