Skip to content

Commit

Permalink
Improve putting together query URL. Use attributes as separate param.
Browse files Browse the repository at this point in the history
  • Loading branch information
miina committed Mar 17, 2018
1 parent ce1f7c6 commit e0fec83
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 21 deletions.
2 changes: 1 addition & 1 deletion components/server-side-render/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Render core/archives preview.
```jsx
<ServerSideRender
block="core/archives"
{ this.props.attributes }
attributes={ this.props.attributes }
/>
```

Expand Down
28 changes: 8 additions & 20 deletions components/server-side-render/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies.
*/
import { isEqual } from 'lodash';
import { isEqual, isObject, map } from 'lodash';

/**
* WordPress dependencies
Expand Down Expand Up @@ -32,11 +32,7 @@ export class ServerSideRender extends Component {

fetch( props ) {
this.setState( { response: null } );
const { block } = props;
const attributes = Object.assign( {}, props );

// Delete 'block' from attributes, only registered block attributes are allowed.
delete attributes.block;
const { block, attributes } = props;

let apiURL = this.getQueryUrlFromObject( {
attributes: attributes,
Expand All @@ -52,20 +48,12 @@ export class ServerSideRender extends Component {
}

getQueryUrlFromObject( obj, prefix ) {
const str = [];
let param;
for ( param in obj ) {
if ( obj.hasOwnProperty( param ) ) {
const key = prefix ? prefix + '[' + param + ']' : param,
value = obj[ param ];
str.push(
( value !== null && 'object' === typeof value ) ?
this.getQueryUrlFromObject( value, key ) :
encodeURIComponent( key ) + '=' + encodeURIComponent( value )
);
}
}
return str.join( '&' );
return map( obj, ( paramValue, paramName ) => {
const key = prefix ? prefix + '[' + paramName + ']' : paramName,
value = obj[ paramName ];
return isObject( paramValue ) ? this.getQueryUrlFromObject( value, key ) :
encodeURIComponent( key ) + '=' + encodeURIComponent( value )
} ).join( '&' );
}

render() {
Expand Down

0 comments on commit e0fec83

Please sign in to comment.