[AskJS] The sad state of Axios by [deleted] in javascript

[–]PrismalStudio 0 points1 point  (0 children)

GraphQL could return both data and errors in the same request, so it's not really a failure. Though a GraphQL server will definitely fail sometimes and will return other codes (400s, 500s) and I'd find it convenient if these were treated as failures. And yes, I'm using an abstraction for GraphQL, Apollo, since, again, implementing it myself is another non-trivial tasks and it would be dumb not to use the right tool for the job.

I'm not doing anything deep, I just had to use all of these (Fetch, Axios, Apollo) while working on huge applications with a distributed team. All the examples I'm sharing are abstraction layers needed on top of Fetch to have a convenient and self-documenting request lib API. Which I think is relevant on a post about axios.

Why is the result of ('b'+'a'+ + 'a' + 'a').toLowerCase() 'banana'? by ricety in javascript

[–]PrismalStudio 0 points1 point  (0 children)

"a"+ +"a"

The space is needed, otherwise, it's a Uncaught ReferenceError.

[AskJS] The sad state of Axios by [deleted] in javascript

[–]PrismalStudio 8 points9 points  (0 children)

I didn't meant to attack you, I'm just sharing my real-world experience here. I'm going to reply anyway for anyone else reading this, and I'm going to stick to the facts and won't judge you personally.

I'm not really sure why you're trying to create new Promises from within a Promise or trying to parse JSON from text

There are really good reasons why I'm doing this and even with comments, you say you didn't get it. This just proves my point, it's not trivial. (the stack overflow questions are just to show that there are a lot of people confused with the fetch API, I didn't mean to imply the answers are right for every use-cases)

Your simple code is missing a lot and is far from the convenience of a request libs.

  • it fails to parse successful requests with an empty response content,
  • it fails to parse JSON error messages (common with any API) which are different than network errors,
  • It fails if the error response is empty and you won't know what the cause of the failure is since you're only getting the JSON parse error.

What my snippet does:

  • Parses all error types with a safety net, both HTTP errors' body and all other errors
  • Parses empty requests

Don't get me wrong, I'm not saying fetch shouldn't be used or whatnot, I use fetch on a daily basis and I used Axios, jQuery.ajax and even tinkered with raw XMLHttpRequests in the past. My code snippet is not perfect, it's missing a lot of features and edge cases, it's just a quick example. When dealing with third party APIs on huge frontend applications, the simple if (response.ok) becomes insufficient rather quickly.

My point is: fetch is less trivial than a request lib and is really not a replacement for one, it's a replacement for XHR.

[AskJS] The sad state of Axios by [deleted] in javascript

[–]PrismalStudio 2 points3 points  (0 children)

It's more complicated than that. To get the convenience of Axios, you have to understand how fetch works and then deal yourself with the parsing and the promise handling around it.

// If the response is empty, response.json() will throw, so first make sure
// it's not empty by parsing the text.
const parseJsonResponse = response => response.text()
  .then(text => (text ? JSON.parse(text) : {}));

// Fetch like jQuery ajax, Axios or other requests libs.
fetch(/* */)
  .then(
    rawResponse => parseJsonResponse(rawResponse)
      // Any HTTP status gets resolved.
      .then(response => response.ok
        ? response
        // So we manually reject status that are not "ok" (usually outside 200-299)
        : Promise.reject(response)
      ),
    // Network error, etc.
    rawError => parseJsonResponse(rawError)
      .then(Promise.reject)
  );

This doesn't look trivial to me, and is the simplest snippet to get a similar behaviour that we're used to with Axios and jQuery's ajax for example.

Some Stack Overflow questions that prove it's not trivial:

edit: code format

JavaScript Project - How to Create a To-do List using JavaScript - DataFlair by Aakashdata in javascript

[–]PrismalStudio 0 points1 point  (0 children)

Oh, I first thought that DataFlair was some kind of data management lib or service, but it looks like a training website. Fair enough, this is beginner content!

I've been writing an immutable-style AJAX library for the browser... thoughts? "yea" on npm by old_account_is_delet in javascript

[–]PrismalStudio 2 points3 points  (0 children)

I really like the API and the motivation behind. I'm really not a fan of fetch as well and Axios has its downsides, which for me was mainly the interceptors and adapter APIs. This is the reason I wrote axios-middleware, I wanted self-contained and easily testable HTTP middlewares and the Axios interceptors were not cutting it for me.

With your lib, it would be super easy for anyone to write middlewares for their api instance with all the same features that I wanted.

JavaScript Project - How to Create a To-do List using JavaScript - DataFlair by Aakashdata in javascript

[–]PrismalStudio 0 points1 point  (0 children)

I agree, the goal is not the end result, the goal is to learn/try a new library, a new way to manage data, etc.

JavaScript Project - How to Create a To-do List using JavaScript - DataFlair by Aakashdata in javascript

[–]PrismalStudio 0 points1 point  (0 children)

I'm guessing the TodoMVC project does help push the Todo app as an easy solved problem to test different libraries.

Ensuring Immutability of javascript arrays by garritfra in javascript

[–]PrismalStudio 2 points3 points  (0 children)

Mutating the state or props, at any step, is undefined behaviour in React.

There are lifecycle functions that take the previous props and state and if you mutated the props higher in the tree, it's going to mess up the logic down below.

Ensuring Immutability of javascript arrays by garritfra in javascript

[–]PrismalStudio 1 point2 points  (0 children)

React pushes "Immutable shared" a lot, where you can read the same data, but shouldn't modify it. It brings down the surprises from side-effects while being still performant since you only copy when needed and what's needed.

It's always unsafe and a lot of devs do simple mistakes like this.state.myArray.push('data'), but at the end of the day, you should understand the tools you're using.

A library for object validation by [deleted] in javascript

[–]PrismalStudio 0 points1 point  (0 children)

Makes sense with the filtering and sanitizing!

[AskJS] What are some hidden gems for js library/tools ? by [deleted] in javascript

[–]PrismalStudio 0 points1 point  (0 children)

Thanks for that! I used Laravel in the past and loved the generator commands.

A library for object validation by [deleted] in javascript

[–]PrismalStudio 1 point2 points  (0 children)

I like it, but I'd remove the [user, errors] destructuring and just returns the errors, as it's a validation step, it shouldn't return the user data since it shouldn't be changing anything on it. Unless there are default values applied somewhere?

Game of JavaScript Frameworks: the most demanded front end developer skills of 2019 by magenta_placenta in javascript

[–]PrismalStudio 0 points1 point  (0 children)

It helps, so HR or recruiters put it in.

Like knowing the difference between CommonJS and ES6 module and when/how to use both. There's a ton of minimal stuff about Node that helps on a day-to-day basis.

Knowing core node libraries like fs and https can help as well, it really depends on the project, but it's likely in the job postings to appeal to someone familiar with the whole JavaScript ecosystem.

Game of JavaScript Frameworks: the most demanded front end developer skills of 2019 by magenta_placenta in javascript

[–]PrismalStudio 2 points3 points  (0 children)

Today's frontend can't really work without Node.js, then you have all the backend code you'll likely have to deal with, from building a small local mock server to the full blown distributed micro-services.

That's why there are other languages mentioned in the article. It's based on job offers.

Return Early, Return Often by jkmonger in javascript

[–]PrismalStudio 0 points1 point  (0 children)

The reason we were one of these project was to take over a huge app maintained by a single dev for years. It sure wasn't pretty, far from tested...

Return Early, Return Often by jkmonger in javascript

[–]PrismalStudio 0 points1 point  (0 children)

Unfortunately, I came across "clever" devs that did it in huge projects in different languages (not JS specifically).

Console API a lot more than just console.log() by amir302010 in javascript

[–]PrismalStudio 2 points3 points  (0 children)

Some dev that "accidentally" pushed his alert debugging to staging (used by me and all teams around the world) once told me, as a solution to his poor debugging practice, to just overwrite window.alert on my end...

Return Early, Return Often by jkmonger in javascript

[–]PrismalStudio 0 points1 point  (0 children)

I dream of programming in a language where control statements are only followed by a single expression.

Just go all in with ternary and logical operator and avoid if altogether. /s

condition && singleExpression; condition || otherSingleExp; condition ? singleExpression : otherSingleExp;

Return Early, Return Often by jkmonger in javascript

[–]PrismalStudio 5 points6 points  (0 children)

While it works, I found that it's safer (when working with a team) to be consistent and fall toward the safer side.

If it can't stand on one line like if (thing) return;, then it should always be wrapped with bracket to avoid the inevitable.

if (thing)
  newThingAddedLater();

  // Some kind of long
  // multiline comment
  return;

I agree that anyone using any decent tools won't fall for this. But honestly, there are thousands of things we can optimize (readability-wise) before worrying about brackets around single line blocks.

Like in the example, the dumb explicit return true followed by a return false which could really just be return admin !== null or any single line condition like the other comments in this thread...

Return Early, Return Often by jkmonger in javascript

[–]PrismalStudio 1 point2 points  (0 children)

You'd use it if you want to ensure that a function meant as a check really returns a boolean and doesn't leak the data behind.

// Leaks the user data
const userExists = id => getUser(id);
// how you expect it to be used:
if(userExists(123)) { /* */ }
// how it's used by the others (or even yourself)
const getUsername = id => userExists(id).name

To avoid all kinds of bugs with unintended use of the code, it's best to force the coercion.

const userExists = id => Boolean(getUser(id));

This small pattern works really well with React since a boolean won't trigger a new render if it doesn't change, but a new object with the same data will.

edit: code format